package com.xmy.cultivate.controller;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.annotaion.ApiMethod;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.response.ArrivalRate;
import com.xmy.cultivate.entity.response.Reconciliation;
import com.xmy.cultivate.entity.views.*;
import com.xmy.cultivate.enums.StatusRecordEnum;
import com.xmy.cultivate.feign.erp_admin.IAdminFeignClient;
import com.xmy.cultivate.respons.AccountingRate;
import com.xmy.cultivate.respons.AssignMoney;
import com.xmy.cultivate.service.AuthorityServic;
import com.xmy.cultivate.service.IGradeService;
import com.xmy.cultivate.respons.ResSchoolDate;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.entity.response.UserSort;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 记上课
 * </p>
 *
 * @author min
 * @since 2022-11-01
 */
@RestController
@RequestMapping("/api/recordCourse")
@Scope("prototype")
public class RecordCourseController extends BaseController {

    @Autowired
    IRecordCourseService iRecordCourseService;


    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    RecordCourseMapper recordCourseMapper;

    @Autowired
    StaffMapper staffMapper;

    @Autowired
    StudentGradeMapper studentGradeMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    AuthorityServic authorityServic;

    @Autowired
    RenewDataMapper renewDataMapper;

    @Autowired
    RepairCourseMapper repairCourseMapper;

    @Autowired
    IGradeService iGradeService;

    @Autowired
    GradeMapper gradeMapper;

    @Autowired
    OrganizationMapper organizationMapper;

    @Autowired
    ICourseSchedulingDetailService iCourseSchedulingDetailService;

    @Autowired
    RoleAdminMapper roleAdminMapper;

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    @Lazy
    IRepairCourseService iRepairCourseService;

    @Autowired
    @Lazy
    IAdminFeignClient iAdminFeignClient;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    IRecordCourseCheckService iRecordCourseCheckService;

    @Autowired
    IRecordCourseLackService iRecordCourseLackService;

    @Autowired
    IStudentGradeService iStudentGradeService;

    @Autowired
    ISchoolQuarterService iSchoolQuarterService;

    @Autowired
    IMqPushService iMqPushService;

    @Autowired
    IEnrollInfoService iEnrollInfoService;

    @Autowired
    IOrderApplyService iOrderApplyService;

    @Autowired
    IStudentSignInService iStudentSignInService;

    @Autowired
    IAuthAdminContentService iAuthAdminContentService;

    @Autowired //如果给redis中保存数据会使用默认的序列化机制，导致redis中保存的对象不可视
    RedisTemplate<Object, Object> redisTemplate;



    @GetMapping("/getSchoolTime")
    public Result getSchoolTime(@RequestParam(value = "schoolId", required = false, defaultValue = "") String schoolId,
                                @RequestParam(value = "gradeId", required = false, defaultValue = "") String gradeId,
                                @RequestParam(value = "teacherId", required = false, defaultValue = "") String teacherId,
                                @RequestParam(value = "lessonType", required = false, defaultValue = "") String lessonType,
                                @RequestParam(value = "schoolDate", required = false, defaultValue = "") String schoolDate,
                                @RequestParam(value = "endSchoolDate", required = false, defaultValue = "") String endSchoolDate) {
        LocalDate localDateNow = LocalDate.now();
        if (StringUtils.isNotBlank(schoolDate)) {
            localDateNow = LocalDate.parse(schoolDate);
        }
        LocalDate endDate = localDateNow;
        if (StringUtils.isNotBlank(endSchoolDate)) {
            endDate = LocalDate.parse(endSchoolDate);
        }

        List<ResSchoolDate> repairCourseList = iCourseSchedulingDetailService.getSchoolDateList(schoolId, gradeId, teacherId, localDateNow.toString(), endDate.toString(), lessonType);
        return new Result(Code.GET_OK, new PageResult(repairCourseList, (long) repairCourseList.size(), 1L), "获取成功");
    }


    /**
     * 到课率、旷课率
     */
    @ApiMethod(value = "home:edu:attendance-rate,home:financial:truancy-rate", description = "到课率,旷课率")
    @GetMapping("/arrivalRate")
    public Result arrivalRate(
            @RequestParam(value = "type", required = false, defaultValue = "1") Integer type,
            @RequestParam(value = "trackId", required = false, defaultValue = "") String trackId,
            @RequestParam(value = "subjectsId", required = false, defaultValue = "") String subjectsId,
            @RequestParam(value = "teacherName", required = false, defaultValue = "") String teacherName,
            @RequestParam(value = "startDate", required = false, defaultValue = "") String startDate,
            @RequestParam(value = "endDate", required = false, defaultValue = "") String endDate,
            @RequestParam(value = "isTeamDetails", required = false, defaultValue = "") String isTeamDetails,
            @RequestParam(value = "classify", required = false, defaultValue = "") String classify,
            @RequestParam(value = "trackType", required = false, defaultValue = "") String trackType,
            @RequestParam(value = "teamId", required = false, defaultValue = "") String teamId,
            @RequestParam(value = "gradeSection", required = false, defaultValue = "") String gradeSection,
            @RequestParam(value = "yearPart", required = false, defaultValue = "") String yearPartParam,
            @RequestParam(value = "quarterNum", required = false, defaultValue = "") String quarterNumParam,
            @RequestParam(value = "schoolId", defaultValue = "") String schoolId,
            @RequestParam(value = "timeStart", required = false, defaultValue = "") String timeStart,
            @RequestParam(value = "timeEnd", required = false, defaultValue = "") String timeEnd,
            @RequestParam(value = "yearClassId", required = false, defaultValue = "") String yearClassId,
            @RequestParam(value = "lessonType", required = false, defaultValue = "1") String lessonType,
            @RequestParam(value = "isCall", required = false, defaultValue = "0") String isCall,
            @RequestParam(value = "startLessonNum", required = false, defaultValue = "") String startLessonNum,
            @RequestParam(value = "endLessonNum", required = false, defaultValue = "") String endLessonNum,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "teacherId", required = false) String teacherId,
            @RequestParam(value = "isRebrush", required = false, defaultValue = "0") String isRebrush, // 0正常，1复刷
            @RequestParam(value = "isYearClass", required = false, defaultValue = "0") String isYearClass // 0正常，1年级到课率
    ) {
        if (name == null || name.isEmpty()) {
            name = null;
        }
        StringBuffer yearClassIdSb = new StringBuffer();
        if (StringUtils.isNotBlank(gradeSection)) {
            String[] sections = gradeSection.split(",");
            for (String section : sections) {
                if (section.equals("0")) {
                    yearClassIdSb.append("1,2");
                } else if (section.equals("1")) {
                    yearClassIdSb.append("3,4,5,6");
                } else if (section.equals("2")) {
                    yearClassIdSb.append("7,8,9");
                } else if (section.equals("3")) {
                    yearClassIdSb.append("10,11,12");
                }
                if (!section.equals(sections[sections.length - 1])) {
                    yearClassIdSb.append(",");
                }
            }
            yearClassId = yearClassIdSb.toString();
        }

        Quarter quarterInfo = iQuarterService.getNowQuarter();

        Integer yearPart = quarterInfo.getYearPart();
        Integer quarterNum = quarterInfo.getNum();
        if (StringUtils.isNotBlank(yearPartParam)) {
            yearPart = Integer.parseInt(yearPartParam);
        }
        if (StringUtils.isNotBlank(quarterNumParam)) {
            quarterNum = Integer.parseInt(quarterNumParam);
        }
        if (StringUtils.isEmpty(subjectsId)) {
            subjectsId = null;
        }

        // 获取权限

        AuthAdminContent authAdminContent = iAuthAdminContentService.getPermissionForTeacherId(yearPart, quarterNum, this.adminId, this.baseSchoolIdStr);

        if (authAdminContent.getIsPerson() == 1) {
            if (!type.equals(1) && !type.equals(2)) {
                return new Result(Code.OK, new PageResult<>(new ArrayList<>(), (long) 0, 1L));
            }
        }
        iAdminFeignClient.findById(1935306785850130432L);
        List<ArrivalRate> renewClassRecordList = iRecordCourseService.arrivalRate(schoolId, subjectsId, yearPart, quarterNum, teacherName, startDate, endDate, type, timeStart, timeEnd, authAdminContent.getSchoolIdList(), Integer.parseInt(lessonType), yearClassId, trackId, isTeamDetails, classify, trackType, teamId, name, teacherId, startLessonNum, endLessonNum, isCall, isRebrush, isYearClass, this.adminId, authAdminContent);
        return new Result(Code.OK, new PageResult<>(renewClassRecordList, (long) renewClassRecordList.size(), 1L));
    }

    /**
     * 数据统计跨模块调用
     *
     * @param type
     * @param trackId
     * @param subjectsId
     * @param teacherName
     * @param startDate
     * @param endDate
     * @param isTeamDetails
     * @param classify
     * @param trackType
     * @param teamId
     * @param gradeSection
     * @param yearPartParam
     * @param quarterNumParam
     * @param schoolId
     * @param timeStart
     * @param timeEnd
     * @param yearClassId
     * @param lessonType
     * @param isCall
     * @param startLessonNum
     * @param endLessonNum
     * @param name
     * @return
     */
    @GetMapping("/arrivalRateIFeign")
    public List<ArrivalRate> arrivalRateIFeign(
            @RequestParam(value = "type", required = false, defaultValue = "1") Integer type,
            @RequestParam(value = "trackId", required = false, defaultValue = "") String trackId,
            @RequestParam(value = "subjectsId", required = false, defaultValue = "") String subjectsId,
            @RequestParam(value = "teacherName", required = false, defaultValue = "") String teacherName,
            @RequestParam(value = "startDate", required = false, defaultValue = "") String startDate,
            @RequestParam(value = "endDate", required = false, defaultValue = "") String endDate,
            @RequestParam(value = "isTeamDetails", required = false, defaultValue = "") String isTeamDetails,
            @RequestParam(value = "classify", required = false, defaultValue = "") String classify,
            @RequestParam(value = "trackType", required = false, defaultValue = "") String trackType,
            @RequestParam(value = "teamId", required = false, defaultValue = "") String teamId,
            @RequestParam(value = "gradeSection", required = false, defaultValue = "") String gradeSection,
            @RequestParam(value = "yearPart", required = false, defaultValue = "") String yearPartParam,
            @RequestParam(value = "quarterNum", required = false, defaultValue = "") String quarterNumParam,
            @RequestParam(value = "schoolId", defaultValue = "") String schoolId,
            @RequestParam(value = "timeStart", required = false, defaultValue = "") String timeStart,
            @RequestParam(value = "timeEnd", required = false, defaultValue = "") String timeEnd,
            @RequestParam(value = "yearClassId", required = false, defaultValue = "") String yearClassId,
            @RequestParam(value = "lessonType", required = false, defaultValue = "1") String lessonType,
            @RequestParam(value = "isCall", required = false, defaultValue = "0") String isCall,
            @RequestParam(value = "startLessonNum", required = false, defaultValue = "") String startLessonNum,
            @RequestParam(value = "endLessonNum", required = false, defaultValue = "") String endLessonNum,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "teacherId", required = false) String teacherId,
            @RequestParam(value = "isRebrush", required = false, defaultValue = "0") String isRebrush, // 0正常，1复刷
            @RequestParam(value = "isYearClass", required = false, defaultValue = "0") String isYearClass // 0正常，1年级到课率
    ) {
        if (name == null || name.isEmpty()) {
            name = null;
        }
        StringBuffer yearClassIdSb = new StringBuffer();
        if (StringUtils.isNotBlank(gradeSection)) {
            String[] sections = gradeSection.split(",");
            for (String section : sections) {
                if (section.equals("0")) {
                    yearClassIdSb.append("1,2");
                } else if (section.equals("1")) {
                    yearClassIdSb.append("3,4,5,6");
                } else if (section.equals("2")) {
                    yearClassIdSb.append("7,8,9");
                } else if (section.equals("3")) {
                    yearClassIdSb.append("10,11,12");
                }
                if (!section.equals(sections[sections.length - 1])) {
                    yearClassIdSb.append(",");
                }
            }
            yearClassId = yearClassIdSb.toString();
        }

        Quarter quarterInfo = iQuarterService.getNowQuarter();

        Integer yearPart = quarterInfo.getYearPart();
        Integer quarterNum = quarterInfo.getNum();
        if (StringUtils.isNotBlank(yearPartParam)) {
            yearPart = Integer.parseInt(yearPartParam);
        }
        if (StringUtils.isNotBlank(quarterNumParam)) {
            quarterNum = Integer.parseInt(quarterNumParam);
        }

        // 获取admin信息
        FenAdminData fenAdminData = iAuthAdminContentService.getAdminData(yearPart, quarterNum);
        // 获取权限
        AuthAdminContent authAdminContent = iAuthAdminContentService.getPermissionForTeacherId(yearPart, quarterNum, fenAdminData.getAdminId(), fenAdminData.getBaseSchoolIdStr());

        List<ArrivalRate> renewClassRecordList = iRecordCourseService.arrivalRate(schoolId, subjectsId, yearPart, quarterNum, teacherName, startDate, endDate, type, timeStart, timeEnd, this.baseSchoolIdList, Integer.parseInt(lessonType), yearClassId, trackId, isTeamDetails, classify, trackType, teamId, name, teacherId, startLessonNum, endLessonNum, isCall, isRebrush, isYearClass, this.adminId, authAdminContent);
        return renewClassRecordList;
    }


    /**
     * 到课率、旷课率详情
     *
     * @return
     */
    @ApiMethod(value = "home:edu:attendance-rate,home:financial:truancy-rate", description = "到课率,旷课率")
    @GetMapping("/arrivalRateDetail")
    public Result arrivalRateDetail(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                    @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                    @RequestParam(value = "yearPart", required = false, defaultValue = "") String yearPartParam,
                                    @RequestParam(value = "quarterNum", required = false, defaultValue = "") String quarterNumParam,
                                    @RequestParam(value = "schoolId", required = false, defaultValue = "") String schoolId,
                                    @RequestParam(value = "gradeId", required = false, defaultValue = "") String gradeId,
                                    @RequestParam(value = "teacherId", required = false, defaultValue = "") String teacherId,
                                    @RequestParam(value = "subjectsId", required = false, defaultValue = "") String subjectsId,
                                    @RequestParam(value = "type", required = false, defaultValue = "") String type,
                                    @RequestParam(value = "startDate", required = false, defaultValue = "") String startDate,
                                    @RequestParam(value = "endDate", required = false, defaultValue = "") String endDate,
                                    @RequestParam(value = "status", required = false, defaultValue = "") String status,
                                    @RequestParam(value = "timeStart", required = false, defaultValue = "") String timeStart,
                                    @RequestParam(value = "timeEnd", required = false, defaultValue = "") String timeEnd,
                                    @RequestParam(value = "lessonType", required = false, defaultValue = "1") String lessonType,
                                    @RequestParam(value = "isCall", required = false, defaultValue = "0") String isCall,
                                    @RequestParam(value = "yearClassId", required = false, defaultValue = "") String yearClassId,
                                    @RequestParam(value = "classify", required = false, defaultValue = "") String classify,
                                    @RequestParam(value = "trackType", required = false, defaultValue = "") String trackType,
                                    @RequestParam(value = "teamId", required = false, defaultValue = "") String teamId,
                                    @RequestParam(value = "gradeSection", required = false, defaultValue = "") String gradeSection,
                                    @RequestParam(value = "startLessonNum", required = false, defaultValue = "") String startLessonNum,
                                    @RequestParam(value = "endLessonNum", required = false, defaultValue = "") String endLessonNum,
                                    @RequestParam(value = "detailType", required = false, defaultValue = "1") String detailType,
                                    @RequestParam(value = "isRebrush", required = false, defaultValue = "0") String isRebrush // 0正常，1复刷
    ) {
        Quarter quarterInfo = iQuarterService.getNowQuarter();
        IPage<RecordCourse> iPage = new Page<>(pageNum, pageSize);

        Integer yearPart = quarterInfo.getYearPart();
        Integer quarterNum = quarterInfo.getNum();
        if (StringUtils.isNotBlank(yearPartParam)) {
            yearPart = Integer.parseInt(yearPartParam);
        }
        if (StringUtils.isNotBlank(quarterNumParam)) {
            quarterNum = Integer.parseInt(quarterNumParam);
        }

        // 获取权限
        AuthAdminContent authAdminContent = iAuthAdminContentService.getPermissionForTeacherId(yearPart, quarterNum, this.adminId, this.baseSchoolIdStr);

        LeadDataRs leadDataRs = authAdminContent.getLeadDataRs();

        if (StringUtils.isNotBlank(teacherId)) {
            if (!teacherId.equals(String.valueOf(leadDataRs.getTeacherId()))) {
                leadDataRs.setTeacherId(0L);
            }
        }

        StringBuffer yearClassIdSb = new StringBuffer();
        if (StringUtils.isNotBlank(gradeSection)) {
            String[] sections = gradeSection.split(",");
            for (String section : sections) {
                if (section.equals("0")) {
                    yearClassIdSb.append("1,2");
                } else if (section.equals("1")) {
                    yearClassIdSb.append("3,4,5,6");
                } else if (section.equals("2")) {
                    yearClassIdSb.append("7,8,9");
                } else if (section.equals("3")) {
                    yearClassIdSb.append("10,11,12");
                }
                if (!section.equals(sections[sections.length - 1])) {
                    yearClassIdSb.append(",");
                }
            }
            yearClassId = yearClassIdSb.toString();
        }

        if (StringUtils.isBlank(yearClassId)) {
            yearClassId = authAdminContent.getYearClassIds();
        } else {
            String leadYearClassId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getYearClassIds(), yearClassId);
            leadDataRs.setYearClassIds(leadYearClassId);

            yearClassId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getYearClassIds(), yearClassId);
        }

        if (StringUtils.isBlank(subjectsId)) {
            subjectsId = authAdminContent.getSubjectsIds();
        } else {
            String leadSubjectsId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSubjectsIds(), subjectsId);
            leadDataRs.setSubjectsIds(leadSubjectsId);

            subjectsId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSubjectsIds(), subjectsId);
        }

        if (StringUtils.isBlank(schoolId)) {
            schoolId = authAdminContent.getSchoolIds();
        } else {
            String leadSchoolId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSchoolIds(), schoolId);
            leadDataRs.setSchoolIds(leadSchoolId);

            schoolId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSchoolIds(), schoolId);
        }


        iRecordCourseService.arrivalRateDetail(iPage, schoolId, subjectsId, yearPart.toString(), quarterNum.toString(), startDate, endDate, gradeId, teacherId, type, status, timeStart, timeEnd, Integer.parseInt(lessonType), detailType, yearClassId, classify, trackType, teamId, startLessonNum, endLessonNum, isCall, isRebrush, authAdminContent, leadDataRs);
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }


    /**
     * 获取消（补）课率列表
     *
     * @param
     * @return
     */
    @ApiMethod(value = "home:edu:leave-makeup-course-rate", description = "请假补课率")
    @GetMapping("/cancellationRate")
    @ApiOperation("获取消课率列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "subjectId", value = "科目id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "startDate", value = "范围起始时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "endDate", value = "范围结束时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "type", value = "类型", required = true, dataType = "String")
    })
    public Result cancellationRate(@RequestParam(value = "schoolId", required = false, defaultValue = "") String schoolId,
                                   @RequestParam(value = "subjectsId", required = false, defaultValue = "") String subjectsId,
                                   @RequestParam(value = "yearPart", required = false, defaultValue = "") Integer yearPart,
                                   @RequestParam(value = "quarterNum", required = false, defaultValue = "") Integer quarterNum,
                                   @RequestParam(value = "startDate", required = false, defaultValue = "") String startDate,
                                   @RequestParam(value = "endDate", required = false, defaultValue = "") String endDate,
                                   @RequestParam(value = "teamId", required = false, defaultValue = "") String teamId,
                                   @RequestParam(value = "classify", required = false, defaultValue = "") String classify,
                                   @RequestParam(value = "type", required = false, defaultValue = "") Integer type,
                                   @RequestParam(value = "yearClassId", required = false, defaultValue = "") String yearClassId,
                                   @RequestParam(value = "trackType", required = false, defaultValue = "") String trackType,
                                   @RequestParam(value = "startLessonNum", required = false, defaultValue = "") String startLessonNum,
                                   @RequestParam(value = "endLessonNum", required = false, defaultValue = "") String endLessonNum,
                                   @RequestParam(value = "classTypeId", required = false, defaultValue = "") String classTypeIdStr,
                                   @RequestParam(value = "lessonType", required = false, defaultValue = "1") String lessonType,
                                   @RequestParam(value = "teacherId", required = false, defaultValue = "") String teacherId
    ) {
        LocalDateTime startDateTime = LocalDateTime.of(LocalDate.parse(startDate), LocalTime.MIN);
        LocalDateTime endDateTime = LocalDateTime.of(LocalDate.parse(endDate), LocalTime.MAX);

        List<CancellationRate> cancellationRates = new ArrayList<>();

        // 获取权限
        AuthAdminContent authAdminContent = iAuthAdminContentService.getPermissionForTeacherId(yearPart, quarterNum, this.adminId, this.baseSchoolIdStr);
        LeadDataRs leadDataRs = authAdminContent.getLeadDataRs();
        if (authAdminContent.getIsPerson() == 1) {
            if (!type.equals(1) && !type.equals(2)) {
                return new Result(Code.OK, new PageResult<>(new ArrayList<>(), (long) 0, 1L));
            }
        }

        if (StringUtils.isBlank(yearClassId)) {
            yearClassId = authAdminContent.getYearClassIds();
        } else {
            String leadYearClassId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getYearClassIds(), yearClassId);
            leadDataRs.setYearClassIds(leadYearClassId);

            yearClassId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getYearClassIds(), yearClassId);
        }

        if (StringUtils.isBlank(subjectsId)) {
            subjectsId = authAdminContent.getSubjectsIds();
        } else {
            String leadSubjectsId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSubjectsIds(), subjectsId);
            leadDataRs.setSubjectsIds(leadSubjectsId);

            subjectsId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSubjectsIds(), subjectsId);
        }

        if (StringUtils.isBlank(schoolId)) {
            schoolId = authAdminContent.getSchoolIds();
        } else {
            String leadSchoolId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSchoolIds(), schoolId);
            leadDataRs.setSchoolIds(leadSchoolId);

            schoolId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSchoolIds(), schoolId);
        }

        // 权限校区id
        String authAdminSchoolId = authAdminContent.getSchoolIdList().stream().map(Object::toString).collect(Collectors.joining(","));

        if (type != 5) {
            cancellationRates = iRecordCourseService.selectCancellationRate(schoolId, yearPart, quarterNum, subjectsId, type, startDateTime, endDateTime, lessonType, yearClassId, classTypeIdStr, startLessonNum, endLessonNum, teacherId, authAdminContent, leadDataRs);
        }

        if (type == 5) {
            cancellationRates = iRecordCourseService.cancellationRateTeamList(schoolId, yearPart, quarterNum, subjectsId, startDateTime, endDateTime, yearClassId, classTypeIdStr, teamId, classify, trackType, startLessonNum, endLessonNum, authAdminContent, leadDataRs);
        }

        if (type == 6) {
            List<CancellationRate> collectList = new ArrayList<>();

            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("year_part", yearPart);
            queryWrapper.eq("quarter_num", quarterNum);
            queryWrapper.eq("pid", 0);
            List<SchoolQuarter> schoolQuarterList = iSchoolQuarterService.list(queryWrapper);

            for (SchoolQuarter schoolQuarter : schoolQuarterList) {
                CancellationRate arrivalRate = new CancellationRate();
                arrivalRate.setSchoolId(schoolQuarter.getSchoolId());
                arrivalRate.setSchoolName(schoolQuarter.getSchoolName());
                arrivalRate.setSchoolPid(schoolQuarter.getPid());
                arrivalRate.setShouldCount(0);
                arrivalRate.setAlreadyCount(0);
                arrivalRate.setNotCount(0);
                arrivalRate.setNowAlreadyCount(0);

                collectList.add(arrivalRate);
            }

            for (CancellationRate arrivalRate : collectList) {
                List<CancellationRate> childRates = new ArrayList<>();
                for (CancellationRate arrivalRateChild : cancellationRates) {
                    if (arrivalRate.getSchoolId().equals(arrivalRateChild.getSchoolId()) || arrivalRate.getSchoolId().equals(arrivalRateChild.getSchoolPid())) {
                        childRates.add(arrivalRateChild);
                        arrivalRate.setShouldCount(arrivalRateChild.getShouldCount() + arrivalRate.getShouldCount());
                        arrivalRate.setAlreadyCount(arrivalRateChild.getAlreadyCount() + arrivalRate.getAlreadyCount());
                        arrivalRate.setNotCount(arrivalRateChild.getNotCount() + arrivalRate.getNotCount());
                        arrivalRate.setNowAlreadyCount(arrivalRateChild.getNowAlreadyCount() + arrivalRate.getNowAlreadyCount());
                    }
                }
                arrivalRate.setChildRateList(childRates);
            }

            cancellationRates = collectList;
        }

        return new Result(Code.OK, new PageResult<>(cancellationRates, (long) cancellationRates.size(), 1L));
    }

    @GetMapping("/cancellationRateIfeign")
    @ApiOperation("获取消课率列表，数据统计用")
    public List<CancellationRate> cancellationRateIfeign(@RequestParam(value = "schoolId", required = false, defaultValue = "") String schoolId,
                                                         @RequestParam(value = "subjectsId", required = false, defaultValue = "") String subjectsId,
                                                         @RequestParam(value = "yearPart", required = false, defaultValue = "") Integer yearPart,
                                                         @RequestParam(value = "quarterNum", required = false, defaultValue = "") Integer quarterNum,
                                                         @RequestParam(value = "startDate", required = false, defaultValue = "") String startDate,
                                                         @RequestParam(value = "endDate", required = false, defaultValue = "") String endDate,
                                                         @RequestParam(value = "teamId", required = false, defaultValue = "") String teamId,
                                                         @RequestParam(value = "classify", required = false, defaultValue = "") String classify,
                                                         @RequestParam(value = "type", required = false, defaultValue = "") Integer type,
                                                         @RequestParam(value = "yearClassId", required = false, defaultValue = "") String yearClassId,
                                                         @RequestParam(value = "trackType", required = false, defaultValue = "") String trackType,
                                                         @RequestParam(value = "startLessonNum", required = false, defaultValue = "") String startLessonNum,
                                                         @RequestParam(value = "endLessonNum", required = false, defaultValue = "") String endLessonNum,
                                                         @RequestParam(value = "classTypeId", required = false, defaultValue = "") String classTypeIdStr,
                                                         @RequestParam(value = "lessonType", required = false, defaultValue = "1") String lessonType,
                                                         @RequestParam(value = "teacherId", required = false, defaultValue = "") String teacherId
    ) {
        LocalDateTime startDateTime = LocalDateTime.of(LocalDate.parse(startDate), LocalTime.MIN);
        LocalDateTime endDateTime = LocalDateTime.of(LocalDate.parse(endDate), LocalTime.MAX);

        List<CancellationRate> cancellationRates = new ArrayList<>();

        // 获取admin信息
        FenAdminData fenAdminData = iAuthAdminContentService.getAdminData(yearPart, quarterNum);
        // 获取权限
        AuthAdminContent authAdminContent = iAuthAdminContentService.getPermissionForTeacherId(yearPart, quarterNum, fenAdminData.getAdminId(), fenAdminData.getBaseSchoolIdStr());
        LeadDataRs leadDataRs = authAdminContent.getLeadDataRs();

        if (StringUtils.isBlank(yearClassId)) {
            yearClassId = authAdminContent.getYearClassIds();
        } else {
            String leadYearClassId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getYearClassIds(), yearClassId);
            leadDataRs.setYearClassIds(leadYearClassId);

            yearClassId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getYearClassIds(), yearClassId);
        }

        if (StringUtils.isBlank(subjectsId)) {
            subjectsId = authAdminContent.getSubjectsIds();
        } else {
            String leadSubjectsId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSubjectsIds(), subjectsId);
            leadDataRs.setSubjectsIds(leadSubjectsId);

            subjectsId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSubjectsIds(), subjectsId);
        }

        if (StringUtils.isBlank(schoolId)) {
            schoolId = authAdminContent.getSchoolIds();
        } else {
            String leadSchoolId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSchoolIds(), schoolId);
            leadDataRs.setSchoolIds(leadSchoolId);

            schoolId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSchoolIds(), schoolId);
        }

        if (type != 5) {
            cancellationRates = iRecordCourseService.selectCancellationRate(schoolId, yearPart, quarterNum, subjectsId, type, startDateTime, endDateTime, lessonType, yearClassId, classTypeIdStr, startLessonNum, endLessonNum, teacherId, authAdminContent, leadDataRs);
        }

        if (type == 5) {
            cancellationRates = iRecordCourseService.cancellationRateTeamList(schoolId, yearPart, quarterNum, subjectsId, startDateTime, endDateTime, yearClassId, classTypeIdStr, teamId, classify, trackType, startLessonNum, endLessonNum, authAdminContent, leadDataRs);
        }

        if (type == 6) {
            List<CancellationRate> collectList = new ArrayList<>();

            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("year_part", yearPart);
            queryWrapper.eq("quarter_num", quarterNum);
            queryWrapper.eq("pid", 0);
            List<SchoolQuarter> schoolQuarterList = iSchoolQuarterService.list(queryWrapper);

            for (SchoolQuarter schoolQuarter : schoolQuarterList) {
                CancellationRate arrivalRate = new CancellationRate();
                arrivalRate.setSchoolId(schoolQuarter.getSchoolId());
                arrivalRate.setSchoolName(schoolQuarter.getSchoolName());
                arrivalRate.setSchoolPid(schoolQuarter.getPid());
                arrivalRate.setShouldCount(0);
                arrivalRate.setAlreadyCount(0);
                arrivalRate.setNotCount(0);
                arrivalRate.setNowAlreadyCount(0);

                collectList.add(arrivalRate);
            }

            for (CancellationRate arrivalRate : collectList) {
                List<CancellationRate> childRates = new ArrayList<>();
                for (CancellationRate arrivalRateChild : cancellationRates) {
                    if (arrivalRate.getSchoolId().equals(arrivalRateChild.getSchoolId()) || arrivalRate.getSchoolId().equals(arrivalRateChild.getSchoolPid())) {
                        childRates.add(arrivalRateChild);
                        arrivalRate.setShouldCount(arrivalRateChild.getShouldCount() + arrivalRate.getShouldCount());
                        arrivalRate.setAlreadyCount(arrivalRateChild.getAlreadyCount() + arrivalRate.getAlreadyCount());
                        arrivalRate.setNotCount(arrivalRateChild.getNotCount() + arrivalRate.getNotCount());
                        arrivalRate.setNowAlreadyCount(arrivalRateChild.getNowAlreadyCount() + arrivalRate.getNowAlreadyCount());
                    }
                }
                arrivalRate.setChildRateList(childRates);
            }

            cancellationRates = collectList;
        }
        return cancellationRates;
    }


    @ApiMethod(value = "home:edu:leave-makeup-course-rate", description = "请假补课率")
    @GetMapping("/cancellationRateDetail")
    public Result cancellationRateDetail(@RequestParam(value = "schoolId", required = false, defaultValue = "") String schoolId,
                                         @RequestParam(value = "teacherId", required = false, defaultValue = "") Long teacherId,
                                         @RequestParam(value = "subjectsId", required = false, defaultValue = "") String subjectsId,
                                         @RequestParam(value = "yearPart", required = false, defaultValue = "") Integer yearPart,
                                         @RequestParam(value = "quarterNum", required = false, defaultValue = "") Integer quarterNum,
                                         @RequestParam(value = "startDate", required = false, defaultValue = "") String startDate,
                                         @RequestParam(value = "endDate", required = false, defaultValue = "") String endDate,
                                         @RequestParam(value = "type", required = false, defaultValue = "") Integer type,
                                         @RequestParam(value = "gradeId", required = false, defaultValue = "") String gradeId,
                                         @RequestParam(value = "detailType", required = false, defaultValue = "") Integer detailType,
                                         @RequestParam(value = "lessonType", required = false, defaultValue = "1") String lessonType,
                                         @RequestParam(value = "yearClassId", required = false, defaultValue = "") String yearClassId,
                                         @RequestParam(value = "classTypeId", required = false, defaultValue = "") String classTypeIdStr,
                                         @RequestParam(value = "teamId", required = false, defaultValue = "") String teamId,
                                         @RequestParam(value = "classify", required = false, defaultValue = "") String classify,
                                         @RequestParam(value = "trackType", required = false, defaultValue = "") String trackType,
                                         @RequestParam(value = "startLessonNum", required = false, defaultValue = "") String startLessonNum,
                                         @RequestParam(value = "endLessonNum", required = false, defaultValue = "") String endLessonNum,
                                         @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                         @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {

        IPage<RecordCourse> iPage = new Page<>(pageNum, pageSize);
        LocalDateTime startDateTime = LocalDateTime.of(LocalDate.parse(startDate), LocalTime.MIN);
        LocalDateTime endDateTime = LocalDateTime.of(LocalDate.parse(endDate), LocalTime.MAX);

        // 获取权限
        AuthAdminContent authAdminContent = iAuthAdminContentService.getPermissionForTeacherId(yearPart, quarterNum, this.adminId, this.baseSchoolIdStr);
        LeadDataRs leadDataRs = authAdminContent.getLeadDataRs();

        if (StringUtils.isBlank(yearClassId)) {
            yearClassId = authAdminContent.getYearClassIds();
        } else {
            String leadYearClassId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getYearClassIds(), yearClassId);
            leadDataRs.setYearClassIds(leadYearClassId);

            yearClassId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getYearClassIds(), yearClassId);
        }

        if (StringUtils.isBlank(subjectsId)) {
            subjectsId = authAdminContent.getSubjectsIds();
        } else {
            String leadSubjectsId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSubjectsIds(), subjectsId);
            leadDataRs.setSubjectsIds(leadSubjectsId);

            subjectsId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSubjectsIds(), subjectsId);
        }

        if (StringUtils.isBlank(schoolId)) {
            schoolId = authAdminContent.getSchoolIds();
        } else {
            String leadSchoolId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSchoolIds(), schoolId);
            leadDataRs.setSchoolIds(leadSchoolId);

            schoolId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSchoolIds(), schoolId);
        }

        if (teacherId != null) {
            if (!teacherId.equals(leadDataRs.getTeacherId())) {
                leadDataRs.setTeacherId(0L);
            }
        }

        if (type != 5) {
            iRecordCourseService.cancellationRateDetail(iPage, schoolId, teacherId, yearPart, quarterNum, subjectsId, type, startDateTime, endDateTime, lessonType, gradeId, detailType, yearClassId, classTypeIdStr, startLessonNum, endLessonNum, authAdminContent, leadDataRs);
        }

        if (type == 5) {
            iRecordCourseService.cancellationRateTeamDetail(iPage, schoolId, teacherId, yearPart, quarterNum, subjectsId, startDateTime, endDateTime, gradeId, detailType, yearClassId, classTypeIdStr, teamId, classify, trackType, startLessonNum, endLessonNum, authAdminContent, leadDataRs);
        }

        return new Result(Code.OK, new PageResult<>(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }


    /**
     * 考勤记录查询
     *
     * @param reMap
     * @return
     */
    @GetMapping("/examinationRecord")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "schoolId", value = "校区id", required = false, dataType = "String")
    })
    @ApiOperation("考勤记录查询")
    public Result examinationRecord(@RequestParam Map reMap) {
        String teacherId = String.valueOf(this.adminId);
        String schoolId = (String) reMap.get("schoolId");
        Staff staff = staffMapper.selectByAdminId(Long.valueOf(teacherId));
        String nowDate = "2023-3-20";
        int laber = authorityServic.get(teacherId);  //设置标志位
        //标志位1为普通老师，标志位2为校长，标志位3为财务或者主管
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("school_date", nowDate);
        queryWrapper.groupBy("teacher_id", "time_start", "time_end");
        if (laber == 1) {
            queryWrapper.eq(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
            queryWrapper.eq("teacher_id", teacherId);
        }
        //如果是校长则可以查询管辖下所有校区
        if (laber == 2) {
            if (staff.getSchoolId().equals(schoolId) || schoolId == null) {
                queryWrapper.eq("school_id", staff.getSchoolId());
                queryWrapper.ne("teacher_id", teacherId);
            }
        }
        //如果是主管和财务则可以查找所选的全部校区
        if (laber == 3) {
            queryWrapper.eq(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
        }
        List<RecordCourse> recordCourseList = iRecordCourseService.selectExamination(queryWrapper, nowDate);
        if (laber == 2) {
            queryWrapper.clear();
            queryWrapper.eq("teacher_id", teacherId);
            queryWrapper.eq(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
            List<RecordCourse> recordCourseListNext = iRecordCourseService.selectExamination(queryWrapper, nowDate);
            recordCourseList.addAll(recordCourseListNext);
        }
        UserSort.sortByData(recordCourseList);
        return new Result(Code.OK, recordCourseList, "");
    }

    @ApiOperation("考勤详情")
    @GetMapping("/examinationDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "gradeId", value = "班级id", required = true, dataType = "String")
    })
    public Result examinationDetail(@RequestParam Map reMap) {
        String gradeId = (String) reMap.get("gradeId");
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("grade_id", gradeId);
        queryWrapper.notIn("course_type", 2, 3);
        queryWrapper.eq("deleted", 0);
        queryWrapper.eq("school_date", "2023-3-20");
        queryWrapper.groupBy("student_id");
        List<RecordCourse> recordCourseList = recordCourseMapper.selectList(queryWrapper);
        queryWrapper.clear();
        for (RecordCourse recordCourse : recordCourseList) {
            queryWrapper.eq("student_id", recordCourse.getStudentId());
            queryWrapper.eq("school_id", recordCourse.getSchoolId());
            queryWrapper.eq("subjects_id", recordCourse.getSubjectsId());
            queryWrapper.groupBy("student_id");
            Integer residue_course_count = orderDetailMapper.selectResidueCourseCount(queryWrapper);
            queryWrapper.clear();
            Student student = studentMapper.selectById(recordCourse.getStudentId());
            recordCourse.setSex(student.getSex());
            recordCourse.setResidueCourseCount(residue_course_count);
            recordCourse.setLeaveCount(this.getSolidCount(Long.valueOf(gradeId), recordCourse.getStudentId(), 2));
        }
        return new Result(Code.OK, recordCourseList, "");
    }

    public Integer getSolidCount(Long gradeId, Long studentId, Integer status) {
        QueryWrapper<RecordCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("grade_id", gradeId);
        queryWrapper.eq("student_id", studentId);
        queryWrapper.eq("status", status);
        queryWrapper.notIn("course_type", 2, 3);
        queryWrapper.eq("deleted", 0);
        Long solidCount = recordCourseMapper.selectCount(queryWrapper);
        return Integer.valueOf(solidCount.toString());
    }

    @GetMapping("semesterStudentCount")
    public Result semesterStudentCount(@RequestParam("subjectsId") String subjectsId, @RequestParam("type") Integer type, @RequestParam("yearPart") String yearPart, @RequestParam("quarter") String quarter) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("sg.status", 1);
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "sg.year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarter), "sg.quarter_num", quarter);
        queryWrapper.eq("sg.subjects_id", subjectsId);
        queryWrapper.inSql("sg.created_at", "\n" +
                "  SELECT MAX(sg2.created_at)\n" +
                "  FROM student_grade sg2\n" +
                "  WHERE sg.student_id = sg2.student_id\n" +
                "    AND sg.school_id = sg2.school_id");
        //type ：1、个人，2、校区老师，3、校长，4、校区
        if (type == 1) {
            queryWrapper.groupBy("g.teacher_id");
        } else if (type == 2) {
            queryWrapper.groupBy("sg.school_id", "g.teacher_id");
        } else if (type == 3) {
            queryWrapper.inSql("g.teacher_id", "select admin_id from role_admin where role_id = 1568160887369994242 ");
            queryWrapper.groupBy("g.teacher_id");
        } else if (type == 4) {
            queryWrapper.groupBy("sg.school_id");
        }
        List<ResidueStatics> residueStudents = renewDataMapper.semesterStudentCount(queryWrapper);
        for (ResidueStatics residueStatic : residueStudents) {
            for (ResidueStatics residueStaticsNext : residueStudents) {
                if (residueStatic.getTeacherId().equals(residueStaticsNext.getTeacherId()) && type != 4) {
                    residueStatic.setStudentNumber(residueStaticsNext.getStudentNumber());
                }
                if (residueStatic.getSchoolId().equals(residueStaticsNext.getSchoolId()) && type == 4) {
                    residueStatic.setStudentNumber(residueStaticsNext.getStudentNumber());
                }
            }
            residueStatic.setTeacherName(repairCourseMapper.getTeacherName(residueStatic.getTeacherId()));
            residueStatic.setSchoolName(recordCourseMapper.getSchoolName(residueStatic.getSchoolId()));
        }
        return new Result(Code.OK, residueStudents, "学期人数统计完成~");
    }

    @GetMapping("gradeList")
    @ApiOperation("班级查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "teacherId", value = "老师id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "schoolId", value = "学校id", required = false, dataType = "String"),
    })
    public Result gradeList(@RequestParam("teacherId") String teacherId,
                            @RequestParam("schoolId") String schoolId,
                            @RequestParam("subjectsId") String subjectsId,
                            @RequestParam("year_part") String yearPart,
                            @RequestParam("quarter") String quarter) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
        queryWrapper.eq(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
        queryWrapper.eq("year_part", yearPart);
        queryWrapper.eq("status", 1);
        List<Grade> gradeList = iGradeService.list(queryWrapper);
        List<Grade> gradeListF = new ArrayList<>();
        for (Grade grade : gradeList) {
            Integer GradeCount = gradeMapper.getgradeCount(grade.getId(), subjectsId, quarter);
            if (GradeCount != 0) {
                grade.setStudentCount(GradeCount);
                gradeListF.add(grade);
            }
        }
        return new Result(Code.OK, gradeListF, "班级查询完成");
    }

    @PostMapping("semesterDetailAll")
    @ApiOperation("学期学生全部明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "类型", required = true, dataType = "String"),
            @ApiImplicitParam(name = "teacherId", value = "老师id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "schoolId", value = "学校id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "gradeId", value = "班级id", required = false, dataType = "String")
    })
    public Result semesterDetailAll(@RequestBody Map reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        String type = (String) reMap.get("type");
        String teacherId = (String) reMap.get("teacherId");
        String schoolId = (String) reMap.get("schoolId");
        String gradeId = (String) reMap.get("gradeId");

        //分类型查找出符合条件的班级
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if (type.equals("1")) {
            queryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
        } else if (type.equals("2")) {
            queryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
            queryWrapper.eq(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
        } else if (type.equals("3")) {
            queryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
        } else if (type.equals("4")) {
            queryWrapper.eq(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
        }
        queryWrapper.eq("status", 1);
        queryWrapper.inSql("created_at", "SELECT MAX(created_at) FROM student_grade GROUP BY student_id");
        queryWrapper.eq(StringUtils.isNotBlank(gradeId), "grade_id", gradeId);
        List<ResidueStudent> residueStudentList = recordCourseMapper.semesterDetailAll(queryWrapper);
        for (ResidueStudent residueStudent : residueStudentList) {
            if (Objects.isNull(teacherId)) {
                teacherId = String.valueOf(iGradeService.getById(gradeId).getTeacherId());
            }
            residueStudent.setTeacherId(teacherId);
            residueStudent.setTeacherName(repairCourseMapper.getTeacherName(residueStudent.getTeacherId()));
            residueStudent.setSchoolName(recordCourseMapper.getSchoolName(residueStudent.getSchoolId()));
            residueStudent.setStudentName(recordCourseMapper.getStudentName(residueStudent.getStudentId()));
            residueStudent.setGradeId(gradeId);
            residueStudent.setGradeName(iGradeService.getOneForId(Long.valueOf(gradeId)).getName());
        }
        // 将 List<ResidueStudent> 转换为 IPage<ResidueStudent>
        Page<ResidueStudent> page = new Page<>(pageNum, pageSize, residueStudentList.size()); // 初始化 Page 对象
        Integer newPage = pageSize * (pageNum - 1);
        Integer endPage = pageSize * pageNum;
        if (pageSize * pageNum > residueStudentList.size()) {
            endPage = residueStudentList.size();
        }
        page.setRecords(residueStudentList.subList(newPage, endPage)); // 设置记录列表
        page.setPages(pageNum); // 设置总页数
        return new Result(Code.OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()), "学生明细查询完成");
    }

    @PostMapping("semesterDetailSub")
    @ApiOperation("学期学生科目明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "类型", required = true, dataType = "String"),
            @ApiImplicitParam(name = "teacherId", value = "老师id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "schoolId", value = "学校id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "gradeId", value = "班级id", required = false, dataType = "String")
    })
    public Result semesterDetailSub(@RequestBody Map reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        String type = (String) reMap.get("type");
        String teacherId = (String) reMap.get("teacherId");
        String schoolId = (String) reMap.get("schoolId");
        List<String> gradeId = (List<String>) reMap.get("gradeId");

        //分类型查找出符合条件的班级
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if (type.equals("1")) {
            queryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
        } else if (type.equals("2")) {
            queryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
            queryWrapper.eq(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
        } else if (type.equals("3")) {
            queryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
        } else if (type.equals("4")) {
            queryWrapper.eq(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
        }
        queryWrapper.eq("status", 1);
        queryWrapper.inSql("created_at", "SELECT MAX(created_at) FROM student_grade GROUP BY student_id");
        queryWrapper.in("grade_id", gradeId);
        List<ResidueStudent> residueStudentList = recordCourseMapper.semesterDetailAll(queryWrapper);
        for (ResidueStudent residueStudent : residueStudentList) {
            if (Objects.isNull(teacherId)) {
                teacherId = String.valueOf(iGradeService.getById(residueStudent.getGradeId()).getTeacherId());
            }
            residueStudent.setTeacherId(teacherId);
            residueStudent.setTeacherName(repairCourseMapper.getTeacherName(residueStudent.getTeacherId()));
            residueStudent.setSchoolName(recordCourseMapper.getSchoolName(residueStudent.getSchoolId()));
            residueStudent.setStudentName(recordCourseMapper.getStudentName(residueStudent.getStudentId()));
            residueStudent.setGradeName(iGradeService.getOneForId(Long.valueOf(residueStudent.getGradeId())).getName());
        }
        // 将 List<ResidueStudent> 转换为 IPage<ResidueStudent>
        Page<ResidueStudent> page = new Page<>(pageNum, pageSize, residueStudentList.size()); // 初始化 Page 对象
        Integer newPage = pageSize * (pageNum - 1);
        Integer endPage = pageSize * pageNum;
        if (pageSize * pageNum > residueStudentList.size()) {
            endPage = residueStudentList.size();
        }
        page.setRecords(residueStudentList.subList(newPage, endPage)); // 设置记录列表
        page.setPages(pageNum); // 设置总页数
        return new Result(Code.OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()), "学生明细查询完成");
    }

    /**
     * 个人的课时提成
     * 3课时 = 1课次
     */
    @GetMapping("oneselfMoney")
    public Result oneselfMoney(@RequestParam Map reMap) {
        String quarterNum = (String) reMap.get("quarterNum");
        String yearPart = (String) reMap.get("yearPart");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");

        Long id = staffMapper.selectIdByAdminId(this.adminId);

        Map<String, Integer> map = new HashMap<>();

        QueryWrapper<RecordCourse> queryWrapper = new QueryWrapper();
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter", quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.ge(StringUtils.isNotBlank(startDate), "school_date", startDate);
        queryWrapper.le(StringUtils.isNotBlank(endDate), "school_date", endDate);
        queryWrapper.eq("teacher_id", id);
        queryWrapper.eq("status", 1);
        queryWrapper.eq("is_deduct_house", 1);
        queryWrapper.eq("deleted", 0);

        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("startDate", startDate);
        hashMap.put("endDate", endDate);
        hashMap.put("teacherId", String.valueOf(id));
        hashMap.put("yearPart", yearPart);
        hashMap.put("quarterNum", quarterNum);


        // 已消课次
        Integer repairCount = iRecordCourseService.getRepairCourse(hashMap).get("repairCount");
        Integer buckleClassHouse = recordCourseMapper.sumBuckleClassHouse(queryWrapper);
        Integer alreadyClass = 0;
        if (repairCount != null) {
            alreadyClass += repairCount;
        }
        if (buckleClassHouse != null) {
            alreadyClass += buckleClassHouse;
        }
        map.put("alreadyClass", alreadyClass);

        //可发放课次提成
        Integer mayMoney = 0;
        Integer cityNum = 0;
        Integer prefectureNum = 0;
        List<RecordCourse> recordCourseList = iRecordCourseService.list(queryWrapper);
        for (RecordCourse recordCourse : recordCourseList) {
            Integer level = organizationMapper.getSchoolLevel(String.valueOf(recordCourse.getSchoolId()));
            if (level == 1) {
                //市
                cityNum += 1;
            } else if (level == 2) {
                //县
                prefectureNum += 1;
            }
        }
        mayMoney = cityNum * 20 + prefectureNum * 17;

        map.put("mayMoney", mayMoney);

        // 未消课次
        Integer unfinishedClass = iRecordCourseService.getRepairCourse(hashMap).get("unfinishedClass");
        map.put("unfinishedClass", unfinishedClass);

        //总人数
        map.put("headcount", iRecordCourseService.headcount(hashMap));

        return new Result(Code.OK, map, "课时提成查询完成");
    }

    /**
     * 迟到率
     */
    @GetMapping("/tardinessRate")
    public Result tardinessRate(@RequestParam Map<String, Object> reMap,
                                @RequestParam(value = "yearPart", required = false, defaultValue = "") String yearPartParam,
                                @RequestParam(value = "quarterNum", required = false, defaultValue = "") String quarterNumParam,
                                @RequestParam(value = "schoolIdList", defaultValue = "") String[] schoolIdList,
                                @RequestParam(value = "timeStart", required = false, defaultValue = "") String timeStart,
                                @RequestParam(value = "timeEnd", required = false, defaultValue = "") String timeEnd,
                                @RequestParam(value = "yearClassId", required = false, defaultValue = "") String yearClassId,
                                @RequestParam(value = "lessonType", required = false, defaultValue = "1") String lessonType,
                                @RequestParam(value = "startLessonNum", required = false, defaultValue = "") String startLessonNum,
                                @RequestParam(value = "endLessonNum", required = false, defaultValue = "") String endLessonNum,
                                @RequestParam(value = "name", required = false) String name,
                                @RequestParam(value = "teacherId", required = false) String teacherId,
                                @RequestParam(value = "isRebrush", required = false, defaultValue = "0") String isRebrush, // 0正常，1复刷
                                @RequestParam(value = "isYearClass", required = false, defaultValue = "0") String isYearClass // 0正常，1年级到课率
    ) {
        if (name == null || name.isEmpty()) {
            name = null;
        }
        String trackId = "";
        if (reMap.get("trackId") != null && !reMap.get("trackId").toString().isEmpty()) {
            trackId = reMap.get("trackId").toString();
        }
        String SubjectsId = (String) reMap.get("subjectsId");
        Quarter quarterInfo = iQuarterService.getNowQuarter();
        Integer yearPart = quarterInfo.getYearPart();
        Integer quarterNum = quarterInfo.getNum();
        if (StringUtils.isNotBlank(yearPartParam)) {
            yearPart = Integer.parseInt(yearPartParam);
        }
        if (StringUtils.isNotBlank(quarterNumParam)) {
            quarterNum = Integer.parseInt(quarterNumParam);
        }

        String isTeamDetails = (String) reMap.get("isTeamDetails");
        String classify = (String) reMap.get("classify");
        String trackType = (String) reMap.get("trackType");
        String teamId = (String) reMap.get("teamId");

        String TeacherName = (String) reMap.get("teacherName");
        String StartDate = (String) reMap.get("startDate");
        String EndDate = (String) reMap.get("endDate");
        if (schoolIdList.length == 0) {
            //schoolIdList = baseSchoolIdStr.split(",");
        }

        String schoolId = null;
        if (reMap.get("schoolId") != null && !reMap.get("schoolId").toString().isEmpty()) {
            schoolId = reMap.get("schoolId").toString();
        }

        Integer type = 1;
        if (reMap.get("type") != null && StringUtils.isNotBlank(reMap.get("type").toString())) {
            type = Integer.parseInt((String) reMap.get("type"));
        }

        // 获取权限
        AuthAdminContent authAdminContent = iAuthAdminContentService.getPermissionForTeacherId(yearPart, quarterNum, this.adminId, this.baseSchoolIdStr);

        if (authAdminContent.getIsPerson() == 1) {
            if (!type.equals(1) && !type.equals(2)) {
                return new Result(Code.OK, new PageResult<>(new ArrayList<>(), (long) 0, 1L));
            }
        }

        List<ArrivalRate> renewClassRecordList = iRecordCourseService.tardinessRate(schoolIdList, SubjectsId, yearPart, quarterNum, TeacherName, StartDate, EndDate, type, timeStart, timeEnd, authAdminContent.getSchoolIdList(), Integer.parseInt(lessonType), schoolId, yearClassId, trackId, isTeamDetails, classify, trackType, teamId, name, startLessonNum, endLessonNum, teacherId, isRebrush, isYearClass, authAdminContent);

        return new Result(Code.OK, new PageResult(renewClassRecordList, (long) renewClassRecordList.size(), 1L));
    }

    @GetMapping("/tardinessRateIFeign")
    public List<ArrivalRate> tardinessRateIFeign(
            @RequestParam(value = "yearPart", required = false, defaultValue = "") String yearPartParam,
            @RequestParam(value = "quarterNum", required = false, defaultValue = "") String quarterNumParam,
            @RequestParam(value = "schoolIdList", defaultValue = "") String[] schoolIdList,
            @RequestParam(value = "timeStart", required = false, defaultValue = "") String timeStart,
            @RequestParam(value = "timeEnd", required = false, defaultValue = "") String timeEnd,
            @RequestParam(value = "yearClassId", required = false, defaultValue = "") String yearClassId,
            @RequestParam(value = "lessonType", required = false, defaultValue = "1") String lessonType,
            @RequestParam(value = "startLessonNum", required = false, defaultValue = "") String startLessonNum,
            @RequestParam(value = "endLessonNum", required = false, defaultValue = "") String endLessonNum,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "subjectsId", required = false) String subjectsId,
            @RequestParam(value = "isTeamDetails", required = false) String isTeamDetails,
            @RequestParam(value = "classify", required = false) String classify,
            @RequestParam(value = "trackType", required = false) String trackType,
            @RequestParam(value = "teamId", required = false) String teamId,
            @RequestParam(value = "teacherName", required = false) String teacherName,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(value = "schoolId", required = false) String schoolId,
            @RequestParam(value = "type", required = false, defaultValue = "1") Integer type,
            @RequestParam(value = "trackId", required = false, defaultValue = "") String trackId,
            @RequestParam(value = "teacherId", required = false) String teacherId,
            @RequestParam(value = "isRebrush", required = false, defaultValue = "0") String isRebrush, // 0正常，1复刷
            @RequestParam(value = "isYearClass", required = false, defaultValue = "0") String isYearClass // 0正常，1年级到课率
    ) {
        if (name == null || name.isEmpty()) {
            name = null;
        }
        Quarter quarterInfo = iQuarterService.getNowQuarter();
        Integer yearPart = quarterInfo.getYearPart();
        Integer quarterNum = quarterInfo.getNum();
        if (StringUtils.isNotBlank(yearPartParam)) {
            yearPart = Integer.parseInt(yearPartParam);
        }
        if (StringUtils.isNotBlank(quarterNumParam)) {
            quarterNum = Integer.parseInt(quarterNumParam);
        }

        // 获取admin信息
        FenAdminData fenAdminData = iAuthAdminContentService.getAdminData(yearPart, quarterNum);
        // 获取权限
        AuthAdminContent authAdminContent = iAuthAdminContentService.getPermissionForTeacherId(yearPart, quarterNum, fenAdminData.getAdminId(), fenAdminData.getBaseSchoolIdStr());

        List<ArrivalRate> renewClassRecordList = iRecordCourseService.tardinessRate(schoolIdList, subjectsId, yearPart, quarterNum, teacherName, startDate, endDate, type, timeStart, timeEnd, this.baseSchoolIdList, Integer.parseInt(lessonType), schoolId, yearClassId, trackId, isTeamDetails, classify, trackType, teamId, name, startLessonNum, endLessonNum, teacherId, isRebrush, isYearClass, authAdminContent);
        return renewClassRecordList;
    }

    /**
     * 迟到详情
     */
    @GetMapping("/tardinessRateDetail")
    public Result tardinessRateDetail(
            @RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
            @RequestParam(value = "yearPart", required = false, defaultValue = "") String yearPartParam,
            @RequestParam(value = "quarterNum", required = false, defaultValue = "") String quarterNumParam,
            @RequestParam(value = "schoolId", required = false, defaultValue = "") String schoolId,
            @RequestParam(value = "gradeId", required = false, defaultValue = "") String gradeId,
            @RequestParam(value = "teacherId", required = false, defaultValue = "") String teacherId,
            @RequestParam(value = "subjectsId", required = false, defaultValue = "") String subjectsId,
            @RequestParam(value = "type", required = false, defaultValue = "") String type,
            @RequestParam(value = "startDate", required = false, defaultValue = "") String startDate,
            @RequestParam(value = "endDate", required = false, defaultValue = "") String endDate,
            @RequestParam(value = "status", required = false, defaultValue = "") String status,
            @RequestParam(value = "punctualityType", required = false, defaultValue = "") String punctualityType,
            @RequestParam(value = "timeStart", required = false, defaultValue = "") String timeStart,
            @RequestParam(value = "timeEnd", required = false, defaultValue = "") String timeEnd,
            @RequestParam(value = "mode", required = false, defaultValue = "") String mode,
            @RequestParam(value = "punctuality", required = false, defaultValue = "2") String punctuality,
            @RequestParam(value = "yearClassId", required = false, defaultValue = "") String yearClassId,
            @RequestParam(value = "classify", required = false, defaultValue = "") String classify,
            @RequestParam(value = "trackType", required = false, defaultValue = "") String trackType,
            @RequestParam(value = "teamId", required = false, defaultValue = "") String teamId,
            @RequestParam(value = "startLessonNum", required = false, defaultValue = "") String startLessonNum,
            @RequestParam(value = "endLessonNum", required = false, defaultValue = "") String endLessonNum,
            @RequestParam(value = "isCall", required = false, defaultValue = "0") String isCall,
            @RequestParam(value = "lessonType", required = false, defaultValue = "1") String lessonType,
            @RequestParam(value = "detailType", required = false, defaultValue = "1") String detailType,
            @RequestParam(value = "isRebrush", required = false, defaultValue = "0") String isRebrush // 0正常，1复刷

    ) {
        Quarter quarterInfo = iQuarterService.getNowQuarter();
        IPage<RecordCourse> iPage = new Page<>(pageNum, pageSize);

        Integer yearPart = quarterInfo.getYearPart();
        Integer quarterNum = quarterInfo.getNum();
        if (StringUtils.isNotBlank(yearPartParam)) {
            yearPart = Integer.parseInt(yearPartParam);
        }
        if (StringUtils.isNotBlank(quarterNumParam)) {
            quarterNum = Integer.parseInt(quarterNumParam);
        }

        // 获取权限
        AuthAdminContent authAdminContent = iAuthAdminContentService.getPermissionForTeacherId(yearPart, quarterNum, this.adminId, this.baseSchoolIdStr);


        LeadDataRs leadDataRs = authAdminContent.getLeadDataRs();

        if (StringUtils.isBlank(yearClassId)) {
            yearClassId = authAdminContent.getYearClassIds();
        } else {
            String leadYearClassId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getYearClassIds(), yearClassId);
            leadDataRs.setYearClassIds(leadYearClassId);

            yearClassId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getYearClassIds(), yearClassId);
        }

        if (StringUtils.isBlank(subjectsId)) {
            subjectsId = authAdminContent.getSubjectsIds();
        } else {
            String leadSubjectsId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSubjectsIds(), subjectsId);
            leadDataRs.setSubjectsIds(leadSubjectsId);

            subjectsId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSubjectsIds(), subjectsId);
        }

        if (StringUtils.isBlank(schoolId)) {
            schoolId = authAdminContent.getSchoolIds();
        } else {
            String leadSchoolId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSchoolIds(), schoolId);
            leadDataRs.setSchoolIds(leadSchoolId);

            schoolId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSchoolIds(), schoolId);
        }

        if (StringUtils.isNotBlank(teacherId)) {
            if (!teacherId.equals(String.valueOf(leadDataRs.getTeacherId()))) {
                leadDataRs.setTeacherId(0L);
            }
        }

        iRecordCourseService.tardinessRateDetail(iPage, schoolId, subjectsId, yearPart.toString(), quarterNum.toString(), startDate, endDate, gradeId, teacherId, type, status, timeStart, timeEnd, Integer.parseInt(lessonType), mode, punctuality, punctualityType, yearClassId, classify, trackType, teamId, startLessonNum, endLessonNum, isCall, detailType, isRebrush, authAdminContent, leadDataRs);
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getTotal()));
    }


    /**
     * 指定账户查看的课时提成
     *
     * @param reMap
     * @return
     */
    @GetMapping("assignMoney")
    public Result assignMoney(@RequestParam Map reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));

        String quarterNum = (String) reMap.get("quarterNum");
        String yearPart = (String) reMap.get("yearPart");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");
        String type = (String) reMap.get("type");
        String subjectId = (String) reMap.get("subjectId");

        Map<String, String> map = new HashMap<>();
        map.put("quarterNum", quarterNum);
        map.put("yearPart", yearPart);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("subjectId", subjectId);
        map.put("type", type);
        map.put("adminId", String.valueOf(this.adminId));
        map.put("isSuper", String.valueOf(this.isSuper));

        List<AssignMoney> classHouseMoney = iRecordCourseService.classHouseMoney(map);

        Page<AssignMoney> page = new Page<>(pageNum, pageSize, classHouseMoney.size()); // 初始化 Page 对象
        Integer newPage = pageSize * (pageNum - 1);
        Integer endPage = pageSize * pageNum;
        if (pageSize * pageNum > classHouseMoney.size()) {
            endPage = classHouseMoney.size();
        }
        page.setRecords(classHouseMoney.subList(newPage, endPage)); // 设置记录列表
        page.setPages(pageNum); // 设置总页数

        //根据所选日期查找季度
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("year_part", yearPart);
        wrapper.le("start_date", startDate);
        wrapper.ge("end_date", endDate);
        Quarter eduQuarter = iQuarterService.getOne(wrapper);

        for (AssignMoney assignMoney : page.getRecords()) {
            Map<String, String> hashMap = new HashMap<>();
            if (type.equals("2") || type.equals("4")) {
                hashMap.put("schoolId", String.valueOf(assignMoney.getSchoolId()));
            }
            hashMap.put("quarterNum", String.valueOf(eduQuarter.getNum()));
            hashMap.put("startDate", startDate);
            hashMap.put("endDate", endDate);
            hashMap.put("yearPart", yearPart);
            hashMap.put("type", type);
            if (!type.equals("4")) {
                hashMap.put("teacherId", String.valueOf(assignMoney.getTeacherId()));
            }
            hashMap.put("isSuper", String.valueOf(this.isSuper));

            //总人数
            assignMoney.setHeadcount(iRecordCourseService.headcount(hashMap));

            //总课次
//            assignMoney.setNumberClass(iRecordCourseService.getAllCourseHouse(hashMap));

            //已消
            Integer repairCourse = iRecordCourseService.getRepairCourse(hashMap).get("repairCount") + assignMoney.getAlreadyClass();
            assignMoney.setAlreadyClass(repairCourse);

            //可发放
            Integer repairMayMoney = iRecordCourseService.getRepairCourse(hashMap).get("repairMayMoney") + assignMoney.getMayMoney();
            assignMoney.setMayMoney(repairMayMoney);

            //未消
            assignMoney.setUnfinishedClass(iRecordCourseService.getRepairCourse(hashMap).get("unfinishedClass"));


        }

        return new Result(Code.OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()), "课时提成查询完成");
    }

    /**
     * 课时核对列表（上课记录）
     */
    @GetMapping("/studentClassLog")
    public Result studentClassLog(@RequestParam Map reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? -1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? -1 : Integer.valueOf((String) reMap.get("pageSize"));
        Page<StudentClassLogRep> iPage = new Page<>(pageNum, pageSize);

        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");
        String schoolId = (String) reMap.get("schoolId");
        String yearClassId = (String) reMap.get("yearClassId");
        String status = (String) reMap.get("status");
        String subjectsId = (String) reMap.get("subjectsId");
        String studentName = (String) reMap.get("studentName");
        String courseType = (String) reMap.get("courseType");// 1正常排课，3补课，4调课，5消课,6缺课补课
        String checkType = (String) reMap.get("checkType");// 是否核对，0未核对，1已核对
        String gradeId = (String) reMap.get("gradeId");
        String staffId = (String) reMap.get("staffId");
        String isOther = (String) reMap.get("isOther");// 0自己带班自己上课 1自己带班其他老师上课 2其他老师带班自己上课

        QueryWrapper<StudentClassLogRep> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(schoolId)) {
            queryWrapper.eq("t1.school_id", schoolId);
        } else {
//            queryWrapper.in("school_id", this.baseSchoolIdList);
        }
        queryWrapper.eq("t1.lesson_type", 1);
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "t1.year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "t1.`quarter`", quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(subjectsId), "t1.subjects_id", subjectsId);
        queryWrapper.eq(StringUtils.isNotBlank(courseType), "t1.course_type", courseType);
        queryWrapper.eq(StringUtils.isNotBlank(yearClassId), "t3.year_class_id", yearClassId);
        queryWrapper.like(StringUtils.isNotBlank(studentName), "t2.name", studentName);
        queryWrapper.eq(StringUtils.isNotBlank(gradeId), "t1.old_grade_id", gradeId);
        queryWrapper.eq("t1.deleted", 0);
//        queryWrapper.ne("is_deduct_house",0);

        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            queryWrapper.between("t1.school_date", startDate, endDate);
        }

        if (StringUtils.isNotBlank(status)) {
            if (status.equals("1")) {
                // 对应的的SQL AND ( `status` = 1 OR ( `status` = 2 AND is_repair = 1 ) )
                queryWrapper.and(wrapper -> wrapper.eq("t1.`status`", 1)
                        .or()
                        .eq("t1.`status`", 2).eq("t1.is_repair", 1));
            } else if (status.equals("2")) {
                queryWrapper.eq("t1.status", 2);
                queryWrapper.ne("t1.is_repair", 1);
            }
        }
        queryWrapper.ne("t1.course_type", 8);

        if (isOther.equals("0")) {
            // 自己带班自己上课
            queryWrapper.eq(StringUtils.isNotBlank(checkType), "t1.check_type", checkType);
            queryWrapper.eq(StringUtils.isNotBlank(staffId), "t1.teacher_id", staffId);
            queryWrapper.apply("(t3.id IS NULL OR (t1.teacher_id = t3.teacher_id))");
        }

        if (isOther.equals("1")) {
            // 自己带班其他老师上课
            queryWrapper.eq(StringUtils.isNotBlank(checkType), "t1.take_check_type", checkType);
            queryWrapper.eq(StringUtils.isNotBlank(staffId), "t3.teacher_id", staffId);
            queryWrapper.apply("t1.teacher_id <> t3.teacher_id");
        }

        if (isOther.equals("2")) {
            // 其他老师带班自己上课
            queryWrapper.eq(StringUtils.isNotBlank(checkType), "t1.check_type", checkType);
            queryWrapper.eq(StringUtils.isNotBlank(staffId), "t1.teacher_id", staffId);
            queryWrapper.apply("t1.teacher_id <> t3.teacher_id");
        }

        iRecordCourseService.studentClassLog(iPage, queryWrapper, yearPart, quarterNum, startDate, endDate, status, schoolId, yearClassId, subjectsId, studentName, courseType, checkType, gradeId, staffId, isOther);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
    }

    /**
     * 课时核对总金额
     */
    @GetMapping("/studentClassTeacherGetMoney")
    public Result studentClassTeacherGetMoney(@RequestParam Map reMap) {
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");
        String schoolId = (String) reMap.get("schoolId");
        String yearClassId = (String) reMap.get("yearClassId");
        String status = (String) reMap.get("status");// 1到课，2请假，3旷课
        String subjectsId = (String) reMap.get("subjectsId");
        String studentName = (String) reMap.get("studentName");
        String courseType = (String) reMap.get("courseType");// 1正常排课，3补课，4调课，5消课,6缺课补课
        String gradeId = (String) reMap.get("gradeId");

        QueryWrapper<StudentClassLogRep> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
        queryWrapper.eq("lesson_type", 1);
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter", quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        queryWrapper.eq(StringUtils.isNotBlank(courseType), "course_type", courseType);
        queryWrapper.eq(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);
        queryWrapper.like(StringUtils.isNotBlank(studentName), "student_name", studentName);
        queryWrapper.like(StringUtils.isNotBlank(gradeId), "grade_id", gradeId);
        queryWrapper.eq("check_type", 1);
        queryWrapper.eq("deleted", 0);

        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            queryWrapper.between("school_date", startDate, endDate);
        }

        if (StringUtils.isNotBlank(status)) {
            if (status.equals("1")) {
                // 对应的的SQL AND ( `status` = 1 OR ( `status` = 2 AND is_repair = 1 ) )
                queryWrapper.and(wrapper -> wrapper.eq("`status`", 1)
                        .or()
                        .eq("`status`", 2).eq("is_repair", 1));
            } else if (status.equals("2")) {
                queryWrapper.eq("status", 2);
                queryWrapper.ne("is_repair", 1);
            }
        }

        Staff staff = iStaffService.getStaffId(this.adminId);
        if (Objects.isNull(staff)) {
            return new Result(Code.OK, 0.00, Code.GET_OK_MSG);
        } else {
            queryWrapper.eq("teacher_id", staff.getId());
        }
        List<String> orderBy = new ArrayList<>();
        orderBy.add("school_date");
        orderBy.add("id");
        queryWrapper.orderByDesc(orderBy);

        BigDecimal money = iRecordCourseService.studentClassTeacherGetMoney(queryWrapper);

        return new Result(Code.OK, money, Code.GET_OK_MSG);
    }

    /**
     * 课时收入记录
     */
//    @GetMapping("/studentClassTeacherRecord")
//    public Result studentClassTeacherRecord(@RequestParam Map reMap) {
//        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? -1 : Integer.valueOf((String) reMap.get("pageNum"));
//        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? -1 : Integer.valueOf((String) reMap.get("pageSize"));
//        Page<StudentClassLogRep> iPage = new Page<>(pageNum, pageSize);
//
//        String yearPart = (String) reMap.get("yearPart");
//        String quarterNum = (String) reMap.get("quarterNum");
//        String startDate = (String) reMap.get("startDate");
//        String endDate = (String) reMap.get("endDate");
//
//        Staff staff = iStaffService.getSatffId(this.adminId);
//
//        QueryWrapper<StudentClassLogRep> wrapper = new QueryWrapper<>();
//        wrapper.eq("t1.lesson_type", 1);
//        wrapper.eq(StringUtils.isNotBlank(yearPart), "t1.year_part", yearPart);
//        wrapper.eq(StringUtils.isNotBlank(quarterNum), "t1.`quarter`", quarterNum);
//        wrapper.eq("t1.deleted", 0);
//        wrapper.eq("t1.check_type", 1);
//        wrapper.in("t1.is_deduct_house", 1, 4);
//        wrapper.in("t1.is_deduct_money", 1, 4);
//        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
//            wrapper.between("t1.school_date", startDate, endDate);
//        }
//        if (staff != null && staff.getId() != null) {
//            wrapper.eq("t1.teacher_id", staff.getId());
//        }
//
//        iRecordCourseService.studentClassLog(iPage, wrapper, yearPart, quarterNum,startDate,endDate, String.valueOf(1));
//
//        return new Result(Code.OK, iPage.getRecords(), Code.GET_OK_MSG);
//    }


    /**
     * 单独编辑到课状态
     */
    @PutMapping("/checkRecordStatus")
    public Result checkRecordStatus(@RequestBody RecordCourse recordCourse) {
        iAdminFeignClient.checkRecordStatus(recordCourse);
        return new Result(Code.OK, "", Code.OK_MSG);
    }


    /**
     * 批量编辑到课状态
     */
    @PutMapping("/batchCheckRecordStatus")
    public Result batchCheckRecordStatus(@RequestBody Map reMap) {
        List<Object> recordCourseList = (List<Object>) reMap.get("recordCourseList");

        for (Object object : recordCourseList) {
            String jsonObject = JSON.toJSONString(object);
            RecordCourse recordCourse = JSONObject.parseObject(jsonObject, RecordCourse.class);
            iAdminFeignClient.checkRecordStatus(recordCourse);
        }

        return new Result(Code.OK, "", Code.OK_MSG);
    }

    /**
     * 单独核对课时
     */
    @PostMapping("/isVerifyRecordClass")
    public Result isVerifyRecordClass(@RequestBody Map reMap) {
        String id = (String) reMap.get("id");
        String checkType = (String) reMap.get("checkType");

        RecordCourse recordCourse = iRecordCourseService.getById(id);

        if (Objects.isNull(recordCourse)) {
            return new Result(Code.ERROR, "", "不存在数据");
        }

        // 判断上课老师和核对老师id是否相同
//        if (isSuper == 1) {
//            return new Result(Code.ERROR, "", "无法核对其它老师的上课记录");
//        }
//        Staff staff = iStaffService.getStaffId(this.adminId);
//        if (!recordCourse.getTeacherId().equals(staff.getId())) {
//            return new Result(Code.ERROR, "", "无法核对其它老师的上课记录");
//        }

        if (recordCourse.getCourseType().equals(8)) {
            recordCourse.setCreatedId(this.adminId);
            Result rs = iAdminFeignClient.tryListenBuckleHouse(recordCourse);
            if (!rs.getCode().equals(Code.OK)) {
                return rs;
            }
        }

        UpdateWrapper<RecordCourse> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        if (this.adminId.equals(recordCourse.getTeacherId())) {
            updateWrapper.set("check_type", checkType);
        } else {
            updateWrapper.set("take_check_type", checkType);
        }
        iRecordCourseService.update(updateWrapper);
        iMqPushService.enrollInfoIsTrue(recordCourse);


        //添加核对信息
        /*iRecordCourseCheckService.addData(recordCourse);

        if (recordCourse.getCourseType().equals(3)){
            RepairCourse repairCourse = iRepairCourseService.getById(recordCourse.getSchedulingDetailId());
            if (repairCourse!=null){
                RecordCourse recordCourseOld = iRecordCourseService.getById(repairCourse.getRecordCourseId());
                if (recordCourseOld!=null){
                    recordCourseOld.setCheckType(1);
                    //把被补课的数据设置为已核对
                    iRecordCourseService.updateById(recordCourseOld);

                    RecordCourseLack recordCourseLack = iRecordCourseLackService.getById(recordCourseOld.getId());
                    if (recordCourseLack != null){
                        recordCourseOld.setBuckleClassHouse(recordCourseLack.getBuckleClassHouse());
                    }
                    //添加核对信息
                    iRecordCourseCheckService.addData(recordCourseOld);
                }
            }
        }*/

        return new Result(Code.OK, "", Code.OK_MSG);
    }


    /**
     * 批量核对课时
     */
    @PostMapping("/batchIsVerifyRecordClass")
    public Result batchIsVerifyRecordClass(@RequestBody Map reMap) {
        List<Object> idList = (List<Object>) reMap.get("idList");
        String checkType = (String) reMap.get("checkType");

        // 判断上课老师和核对老师id是否相同
//        if (isSuper == 1) {
//            return new Result(Code.ERROR, "", "无法核对其它老师的上课记录");
//        }

        for (Object object : idList) {
            String jsonObject = JSON.toJSONString(object);
            RecordCourse recordCourseParam = JSONObject.parseObject(jsonObject, RecordCourse.class);
            RecordCourse recordCourse = iRecordCourseService.getById(recordCourseParam.getId());

//            Staff staff = iStaffService.getStaffId(this.adminId);
//            if (!recordCourse.getTeacherId().equals(staff.getId())) {
//                return new Result(Code.ERROR, "", "无法核对其它老师的上课记录");
//            }


            if (this.adminId.equals(recordCourse.getTeacherId())) {
                recordCourse.setCheckType(Integer.valueOf(checkType));
            } else {
                recordCourse.setTakeCheckType(Integer.valueOf(checkType));
            }
            iRecordCourseService.updateById(recordCourse);
            iMqPushService.enrollInfoIsTrue(recordCourse);

            //添加核对信息
            /*iRecordCourseCheckService.addData(recordCourse);

            if (recordCourse.getCourseType().equals(3)){
                RepairCourse repairCourse = iRepairCourseService.getById(recordCourse.getSchedulingDetailId());
                if (repairCourse!=null){
                    RecordCourse recordCourseOld = iRecordCourseService.getById(repairCourse.getRecordCourseId());
                    if (recordCourseOld!=null){
                        recordCourseOld.setCheckType(1);
                        //把被补课的数据设置为已核对
                        iRecordCourseService.updateById(recordCourseOld);

                        RecordCourseLack recordCourseLack = iRecordCourseLackService.getById(recordCourseOld.getId());
                        if (recordCourseLack != null){
                            recordCourseOld.setBuckleClassHouse(recordCourseLack.getBuckleClassHouse());
                        }
                        //添加核对信息
                        iRecordCourseCheckService.addData(recordCourseOld);
                    }
                }
            }*/
        }

        return new Result(Code.SAVE_OK, "", Code.OK_MSG);
    }

    /**
     * 课时核对列表
     */
    @ApiMethod(value = "home:financial:verify-rate", description = "课时核对率")
    @GetMapping("/studentClassLogRate")
    public Result studentClassLogRate(@RequestParam Map reMap) {
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");
        String type = (String) reMap.get("type");
        String schoolId = (String) reMap.get("schoolId");
        String subjectsId = (String) reMap.get("subjectsId");

        AuthAdminContent authAdminContent = iAuthAdminContentService.getPermissionForTeacherId(Integer.parseInt(yearPart), Integer.parseInt(quarterNum), this.adminId, this.baseSchoolIdStr);
        LeadDataRs leadDataRs = authAdminContent.getLeadDataRs();

        List<StudentClassLogRep> recordCourseList = new ArrayList<>();
        if (authAdminContent.getIsPerson() == 1) {
            if (!type.equals("1") && !type.equals("2")) {
                return new Result(Code.OK, new PageResult(recordCourseList, (long) recordCourseList.size(), 1L));
            }
        }

        if (StringUtils.isBlank(subjectsId)) {
            subjectsId = authAdminContent.getSubjectsIds();
        } else {
            String leadSubjectsId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSubjectsIds(), subjectsId);
            leadDataRs.setSubjectsIds(leadSubjectsId);

            subjectsId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSubjectsIds(), subjectsId);
        }

        if (StringUtils.isBlank(schoolId)) {
            schoolId = authAdminContent.getSchoolIds();
        } else {
            String leadSchoolId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSchoolIds(), schoolId);
            leadDataRs.setSchoolIds(leadSchoolId);

            schoolId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSchoolIds(), schoolId);
        }

        recordCourseList = iRecordCourseService.studentClassLogRate(schoolId, startDate, endDate, subjectsId, yearPart, quarterNum, type, authAdminContent, leadDataRs);

        return new Result(Code.OK, recordCourseList, Code.GET_OK_MSG);
    }

    /**
     * 课时核对详情
     */
    @ApiMethod(value = "home:financial:verify-rate", description = "课时核对率")
    @GetMapping("/studentClassLogParticulars")
    public Result studentClassLogParticulars(@RequestParam Map reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        Page<StudentClassLogRep> iPage = new Page<>(pageNum, pageSize);

        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");
        String subjectsId = (String) reMap.get("subjectsId");
        String teacherId = (String) reMap.get("teacherId");
        String schoolId = (String) reMap.get("schoolId");
        String checkType = (String) reMap.get("checkType");

        QueryWrapper<StudentClassLogRep> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("lesson_type", 1);
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter", quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        queryWrapper.eq(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
        queryWrapper.eq("deleted", 0);
        queryWrapper.ne("course_type", 8);

        if (StringUtils.isNotBlank(teacherId)) {
            queryWrapper.and(wrapper -> wrapper
                    .eq("teacher_id", teacherId)
                    .or()
                    .eq("take_teacher_id", teacherId));
        }

        if (StringUtils.isNotBlank(checkType)) {
//            if (checkType.equals("1")) {
            queryWrapper.and(wrapper ->
                    wrapper.or(w -> w.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId).eq("attend_check_type", checkType))
                            .or(w -> w.eq(StringUtils.isNotBlank(teacherId), "take_teacher_id", teacherId)
                                    .eq("take_check_type", checkType)
                                    .apply("teacher_id <> take_teacher_id"))
            );
//            } else if (checkType.equals("0")) {
//                queryWrapper.and(wrapper ->
//                        wrapper.or(w -> w.eq("teacher_id", teacherId).eq("check_type", 0))
//                                .or(w -> w.eq("take_teacher_id", teacherId)
//                                        .eq("take_check_type", 0)
//                                        .ne("teacher_id", "take_teacher_id"))
//                );
//            }
        }

        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            queryWrapper.between("school_date", startDate, endDate);
        }

//        iRecordCourseService.studentClassLogParticulars(iPage, queryWrapper);


        AuthAdminContent authAdminContent = iAuthAdminContentService.getPermissionForTeacherId(Integer.parseInt(yearPart), Integer.parseInt(quarterNum), this.adminId, this.baseSchoolIdStr);
        LeadDataRs leadDataRs = authAdminContent.getLeadDataRs();

        if (StringUtils.isBlank(subjectsId)) {
            subjectsId = authAdminContent.getSubjectsIds();
        } else {
            String leadSubjectsId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSubjectsIds(), subjectsId);
            leadDataRs.setSubjectsIds(leadSubjectsId);

            subjectsId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSubjectsIds(), subjectsId);
        }

        if (StringUtils.isBlank(schoolId)) {
            schoolId = authAdminContent.getSchoolIds();
        } else {
            String leadSchoolId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSchoolIds(), schoolId);
            leadDataRs.setSchoolIds(leadSchoolId);

            schoolId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSchoolIds(), schoolId);
        }

        if (StringUtils.isNotBlank(teacherId)) {
            if (!teacherId.equals(String.valueOf(leadDataRs.getTeacherId()))) {
                leadDataRs.setTeacherId(0L);
            }
        }
        iRecordCourseService.studentClassLogParticulars2(iPage, yearPart, quarterNum, startDate, endDate, schoolId, subjectsId, checkType, teacherId, "1", "0", authAdminContent, leadDataRs);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
    }

    /**
     * 扣课时前确认
     *
     * @param recordCourseParam
     * @return
     */
    @PostMapping("/buckleHouseAffirm")
    public Result buckleHouseAffirm(@RequestBody RecordCourse recordCourseParam) {

        RecordCourse recordCourse = iRecordCourseService.getById(recordCourseParam.getId());
        if (recordCourse == null) {
            return new Result(Code.ERROR, "", "上课记录不存在");
        }
        if (!recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
            return new Result(Code.ERROR, "", "到课的才能扣课时");
        }
        if (recordCourse.getIsDeductHouse().equals(1) && recordCourse.getIsDeductMoney().equals(1)) {
            return new Result(Code.ERROR, "", "已扣课时，不要重复操作");
        }
        Long useCourseCount = iStudentGradeService.getStudentUseCourseCountAllSchool(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getSubjectsId(), recordCourse.getStudentId(), recordCourse.getLessonType());
        if (useCourseCount < 45) {
            return new Result(Code.ERROR, "", "此学生还未上到15课次，不能操作扣课时");
        }
        RecordCourse recordCourseLeave = iRecordCourseService.getLeaveData(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getLessonType(), recordCourse.getStudentId(), recordCourse.getSubjectsId());
        if (recordCourseLeave != null) {
            return new Result(Code.OK, "", "本次将扣除：" + recordCourseLeave.getSchoolDate() + "日请假未补的课次");
        }
        return new Result(Code.OK, "", "此学生已经上满15课次，本次将扣1次课次");
    }

    /**
     * 扣课时
     *
     * @param recordCourseParam
     * @return
     */
    @PostMapping("/buckleHouse")
    public Result buckleHouse(@RequestBody RecordCourse recordCourseParam) {
        RecordCourse recordCourse = iRecordCourseService.getById(recordCourseParam.getId());
        if (recordCourse == null) {
            return new Result(Code.ERROR, "", "上课记录不存在");
        }
        if (!recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
            return new Result(Code.ERROR, "", "状态为“到课”才能扣课时");
        }
        if (recordCourse.getIsDeductHouse().equals(1)) {
            return new Result(Code.ERROR, "", "已扣课时，不要重复操作");
        }
        Long useCourseCount = iStudentGradeService.getStudentUseCourseCountAllSchool(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getSubjectsId(), recordCourse.getStudentId(), recordCourse.getLessonType());
        if (useCourseCount < 45) {
            return new Result(Code.ERROR, "", "此学生还未上到15课次，不能操作扣课时");
        }
        return iRecordCourseService.buckleCourseForHandle(recordCourse.getId());
    }

    /**
     * 查询是否有未核对课时的数据
     *
     * @param reMap
     * @return
     */
    @GetMapping("/uncheckedCount")
    public Result uncheckedCount(@RequestParam Map reMap) {
        String staffId = (String) reMap.get("staffId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");

        Page<StudentClassLogRep> iPage = new Page<>(-1, -1);

        if (staffId.equals("1568138350324350975")) {
            return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
        }

        AuthAdminContent authAdminContent = iAuthAdminContentService.getPermissionForTeacherId(Integer.parseInt(yearPart), Integer.parseInt(quarterNum), this.adminId, this.baseSchoolIdStr);
        LeadDataRs leadDataRs = authAdminContent.getLeadDataRs();

        List<StudentClassLogRep> studentClassLogRepList = new ArrayList<>();

        String redisIdKey = "uncheckedCount::" + yearPart + "-" + quarterNum + "-" + staffId;
        Object o = redisTemplate.opsForValue().get(redisIdKey);
        Integer total = 0;
        if (Objects.isNull(o)) {
            iRecordCourseService.studentClassLogParticulars2(iPage, yearPart, quarterNum, null, null, null, null, "0", staffId, "1", "1", authAdminContent, leadDataRs);
            studentClassLogRepList = iPage.getRecords();
            for (StudentClassLogRep studentClassLogRep : studentClassLogRepList) {
                if (studentClassLogRep.getTotal() != null) {
                    total = studentClassLogRep.getTotal();
                }
            }
            //已经没有的添加到缓存，下次不需要再通过sql获取
            if (total.equals(0)) {
                // 获取当前时间
                LocalDateTime now = LocalDateTime.now();
                // 计算第二天的日期
                LocalDateTime tomorrow = now.plusDays(1);
                // 设置为第二天的5点
                LocalDateTime targetTime = tomorrow.withHour(5).withMinute(0).withSecond(0).withNano(0);
                // 计算时间差
                Duration duration = Duration.between(now, targetTime);
                // 获取时间差的小时数,保存时间在第二天5点前
                long hours = duration.toHours();
                if (hours >= 1) {
                    redisTemplate.opsForValue().set(redisIdKey, total, hours, TimeUnit.HOURS);
                }
            }
        } else {
            total = (Integer) redisTemplate.opsForValue().get(redisIdKey);
            StudentClassLogRep studentClassLogRep = new StudentClassLogRep();
            studentClassLogRep.setTotal(total);
            studentClassLogRepList.add(studentClassLogRep);
        }

        return new Result(Code.OK, new PageResult(studentClassLogRepList, iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
    }


    /**
     * 财务完成率列表
     */
    @GetMapping("/getAccountingRate")
    public Result getAccountingRate(@RequestParam Map<String, String> reMap) {
        int pageNum = -1;
        int pageSize = -1;
        IPage<EnrollDetail> iPage = new Page<>(pageNum, pageSize);

        String type = StringUtils.isNotBlank(reMap.get("type")) ? reMap.get("type") : "4";
        String isDetails = StringUtils.isNotBlank(reMap.get("isDetails")) ? reMap.get("isDetails") : "0";
        String schoolId = reMap.get("schoolId");
        String subjectsId = reMap.get("subjectsId");
        String startDate = reMap.get("startDate");
        String endDate = reMap.get("endDate");
        String checkType = reMap.get("checkType");
        String studentName = reMap.get("studentName");
        String teacherName = reMap.get("teacherName");
        String yearClassId = reMap.get("yearClassId");
        String yearPart = reMap.get("yearPart");
        String quarterNum = reMap.get("quarterNum");
        String isTrueData = reMap.get("isTrueData");

        if (yearPart == null || quarterNum == null) {
            Quarter eduQuarter = iQuarterService.getNowQuarter();
            if (eduQuarter == null) {
                return new Result(Code.ERROR, "未获取到默认年份、学期信息", "请选择年份、学期");
            }
            yearPart = eduQuarter.getYearPart().toString();
            quarterNum = eduQuarter.getNum().toString();
        }

        // 获取权限
        AuthAdminContent authAdminContent = iAuthAdminContentService.getPermissionForTeacherId(Integer.parseInt(yearPart), Integer.parseInt(quarterNum), this.adminId, this.baseSchoolIdStr);
        LeadDataRs leadDataRs = authAdminContent.getLeadDataRs();
        if (authAdminContent.getIsPerson() == 1) {
//            if (!type.equals("1") && !type.equals("2")) {
//                return new Result(Code.OK, new PageResult<>(new ArrayList<>(), (long) 0, 1L));
//            }
        }

        if (StringUtils.isBlank(yearClassId)) {
            yearClassId = authAdminContent.getYearClassIds();
        } else {
            leadDataRs.setYearClassIds(yearClassId);
        }
        if (StringUtils.isBlank(subjectsId)) {
            subjectsId = authAdminContent.getSubjectsIds();
        } else {
            leadDataRs.setSubjectsIds(subjectsId);
        }
        if (StringUtils.isBlank(schoolId)) {
            schoolId = authAdminContent.getSchoolIdList().stream().map(Object::toString).collect(Collectors.joining(","));
        } else {
            leadDataRs.setSchoolIds(schoolId);
        }

        // 招生核对率
        IPage<EnrollDetail> enrollDetailIPage = iEnrollInfoService.getParticularsRate(iPage, schoolId, subjectsId, startDate, endDate, checkType, studentName, teacherName, yearClassId, yearPart, quarterNum, isTrueData, type, 0);

        // 课时核对率
        List<StudentClassLogRep> recordCourseList = iRecordCourseService.studentClassLogRate(schoolId, startDate, endDate, subjectsId, yearPart, quarterNum, type, authAdminContent, leadDataRs);

        // 确认率
        List<Reconciliation> reconciliations = iOrderApplyService.reconciliationRate(yearPart, quarterNum, subjectsId, startDate, endDate);

        // 获取所有校区id
        List<Organization> schoolList = iOrganizationService.list(new QueryWrapper<Organization>()
                .eq("type", 1)
                .eq("status", 1)
                .eq(StringUtils.isNotBlank(schoolId), "id", schoolId));

        List<AccountingRate> accountingRateList = new ArrayList<>();

        if (isDetails.equals("0")) {
            for (Organization school : schoolList) {
                AccountingRate accountingRate = new AccountingRate();
                accountingRate.setSchoolId(school.getId());
                accountingRate.setSchoolName(school.getName());

                // 总数
                Integer totalNum = 0;
                // 已核对
                Integer yetNum = 0;
                // 未核对
                Integer notNum = 0;

                // 招生核对率
                for (EnrollDetail enrollDetail : enrollDetailIPage.getRecords()) {
                    if (school.getId().equals(enrollDetail.getSchoolId())) {
                        totalNum += enrollDetail.getPeopleTotal();
                        yetNum += enrollDetail.getVerifiedNum();
                        notNum += enrollDetail.getNotVerifiedNum();
                    }
                }

                // 课时核对率
                for (StudentClassLogRep recordCourse : recordCourseList) {
                    if (school.getId().equals(recordCourse.getSchoolId())) {
                        totalNum += recordCourse.getStudentCount();
                        yetNum += recordCourse.getIsCheckCount();
                        notNum += (recordCourse.getStudentCount() - recordCourse.getIsCheckCount());
                    }
                }

                // 确认率
                for (Reconciliation reconciliation : reconciliations) {
                    if (school.getId().equals(reconciliation.getSchoolId())) {
                        totalNum += reconciliation.getTotalRecords();
                        yetNum += reconciliation.getCheckedRecords();
                        notNum += reconciliation.getUncheckedRecords();
                    }
                }

                accountingRate.setTotalNum(totalNum);
                accountingRate.setYetNum(yetNum);
                accountingRate.setNotNum(notNum);
                accountingRateList.add(accountingRate);
            }

        } else if (isDetails.equals("1")) {

            for (Organization school : schoolList) {
                // 招生核对率
                for (EnrollDetail enrollDetail : enrollDetailIPage.getRecords()) {
                    if (school.getId().equals(enrollDetail.getSchoolId())) {
                        AccountingRate accountingRate = new AccountingRate();
                        accountingRate.setSchoolId(school.getId());
                        accountingRate.setSchoolName(school.getName());
                        accountingRate.setTotalNum(enrollDetail.getPeopleTotal());
                        accountingRate.setYetNum(enrollDetail.getVerifiedNum());
                        accountingRate.setNotNum(enrollDetail.getNotVerifiedNum());
                        accountingRate.setType(1);
                        accountingRateList.add(accountingRate);
                    }
                }

                // 课时核对率
                for (StudentClassLogRep recordCourse : recordCourseList) {
                    if (school.getId().equals(recordCourse.getSchoolId())) {
                        AccountingRate accountingRate = new AccountingRate();
                        accountingRate.setSchoolId(school.getId());
                        accountingRate.setSchoolName(school.getName());
                        accountingRate.setTotalNum(recordCourse.getStudentCount());
                        accountingRate.setYetNum(recordCourse.getIsCheckCount());
                        accountingRate.setNotNum(recordCourse.getStudentCount() - recordCourse.getIsCheckCount());
                        accountingRate.setType(2);
                        accountingRateList.add(accountingRate);
                    }
                }

                // 确认率
                for (Reconciliation reconciliation : reconciliations) {
                    if (school.getId().equals(reconciliation.getSchoolId())) {
                        AccountingRate accountingRate = new AccountingRate();
                        accountingRate.setSchoolId(school.getId());
                        accountingRate.setSchoolName(school.getName());
                        accountingRate.setTotalNum(reconciliation.getTotalRecords());
                        accountingRate.setYetNum(reconciliation.getCheckedRecords());
                        accountingRate.setNotNum(reconciliation.getUncheckedRecords());
                        accountingRate.setType(3);
                        accountingRateList.add(accountingRate);
                    }
                }
            }
        }

        return new Result(Code.OK, accountingRateList, Code.GET_OK_MSG);
    }

    /**
     * 招生明细-招生核对率详情
     */
    @GetMapping("/getParticularsRateDetail")
    public Result getParticularsRateDetail(@RequestParam Map<String, String> reMap) {
        int pageNum = StringUtils.isEmpty(reMap.get("pageNum")) ? 1 : Integer.parseInt(reMap.get("pageNum"));
        int pageSize = StringUtils.isEmpty(reMap.get("pageSize")) ? 10 : Integer.parseInt(reMap.get("pageSize"));
        IPage<EnrollDetail> iPage = new Page<>(pageNum, pageSize);

        String type = StringUtils.isNotBlank(reMap.get("type")) ? reMap.get("type") : "4";

        String schoolId = reMap.get("schoolId");
        String subjectsId = reMap.get("subjectsId");
        String startDate = reMap.get("startDate");
        String endDate = reMap.get("endDate");
        String checkType = reMap.get("checkType");
        String studentName = reMap.get("studentName");
        String teacherName = reMap.get("teacherName");
        String yearClassId = reMap.get("yearClassId");
        String yearPart = reMap.get("yearPart");
        String quarterNum = reMap.get("quarterNum");
        String isTrueData = reMap.get("isTrueData");

        iEnrollInfoService.getParticularsRate(iPage, schoolId, subjectsId, startDate, endDate, checkType, studentName, teacherName, yearClassId, yearPart, quarterNum, isTrueData, type, 1);
        return new Result(Code.OK, new PageResult<>(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    /**
     * 刷题到勤
     */
    @GetMapping("/getBrushQuestionsDiligently")
    public Result getBrushQuestionsDiligently(@RequestParam(value = "yearPart", required = false, defaultValue = "") String yearPartParam,
                                              @RequestParam(value = "quarterNum", required = false, defaultValue = "") String quarterNumParam,
                                              @RequestParam(value = "schoolId", required = false, defaultValue = "") String schoolId,
                                              @RequestParam(value = "gradeId", required = false, defaultValue = "") String gradeId,
                                              @RequestParam(value = "teacherId", required = false, defaultValue = "") String teacherId,
                                              @RequestParam(value = "subjectsId", required = false, defaultValue = "") String subjectsId,
                                              @RequestParam(value = "studentName", required = false, defaultValue = "") String studentName,
                                              @RequestParam(value = "teacherName", required = false, defaultValue = "") String teacherName,
                                              @RequestParam(value = "startDate", required = false, defaultValue = "") String startDate,
                                              @RequestParam(value = "endDate", required = false, defaultValue = "") String endDate,
                                              @RequestParam(value = "status", required = false, defaultValue = "0") String status,// 0全部，1在校，2离校，3未到
                                              @RequestParam(value = "timeStart", required = false, defaultValue = "") String timeStart,
                                              @RequestParam(value = "timeEnd", required = false, defaultValue = "") String timeEnd,
                                              @RequestParam(value = "lessonType", required = false, defaultValue = "3") String lessonType,
                                              @RequestParam(value = "yearClassId", required = false, defaultValue = "") String yearClassId,
                                              @RequestParam(value = "gradeSection", required = false, defaultValue = "") String gradeSection,
                                              @RequestParam(value = "startLessonNum", required = false, defaultValue = "") String startLessonNum,
                                              @RequestParam(value = "endLessonNum", required = false, defaultValue = "") String endLessonNum,
                                              @RequestParam(value = "type", required = false, defaultValue = "1") Integer type,// 1正常列表，2老师列表
                                              @RequestParam(value = "isRebrush", required = false, defaultValue = "0") String isRebrush, // 0正常，1复刷
                                              @RequestParam(value = "schoolType", required = false, defaultValue = "0") String schoolType // 在校类型，0全部，1正常，2预警，3超时，4写题，5订正，6超时（更新后的）
    ) {
        Quarter quarterInfo = iQuarterService.getNowQuarter();

        Integer yearPart = quarterInfo.getYearPart();
        Integer quarterNum = quarterInfo.getNum();
        if (StringUtils.isNotBlank(yearPartParam)) {
            yearPart = Integer.parseInt(yearPartParam);
        }
        if (StringUtils.isNotBlank(quarterNumParam)) {
            quarterNum = Integer.parseInt(quarterNumParam);
        }

        StringBuilder yearClassIdSb = new StringBuilder();
        if (StringUtils.isNotBlank(gradeSection)) {
            String[] sections = gradeSection.split(",");
            for (String section : sections) {
                if (section.equals("0")) {
                    yearClassIdSb.append("1,2");
                } else if (section.equals("1")) {
                    yearClassIdSb.append("3,4,5,6");
                } else if (section.equals("2")) {
                    yearClassIdSb.append("7,8,9");
                } else if (section.equals("3")) {
                    yearClassIdSb.append("10,11,12");
                }
                if (!section.equals(sections[sections.length - 1])) {
                    yearClassIdSb.append(",");
                }
            }
            yearClassId = yearClassIdSb.toString();
        }

        List<RecordCourse> recordCourseList = iRecordCourseService.getBrushQuestionsDiligently(schoolId, subjectsId, yearPart.toString(), quarterNum.toString(), startDate, endDate, gradeId, teacherId, status, timeStart, timeEnd, Integer.parseInt(lessonType), yearClassId, startLessonNum, endLessonNum, isRebrush, 1, studentName, schoolType, teacherName, type);
        Map<String, Object> resultData = new HashMap<>();
        resultData.put("records", recordCourseList);
        resultData.put("total", recordCourseList.size());

        HashMap<String, Integer> map = new HashMap<>();
        List<RecordCourse> recordCourseCountList = iRecordCourseService.getBrushQuestionsDiligently(schoolId, subjectsId, yearPart.toString(), quarterNum.toString(), startDate, endDate, gradeId, teacherId, status, timeStart, timeEnd, Integer.parseInt(lessonType), yearClassId, startLessonNum, endLessonNum, isRebrush, 2, studentName, schoolType, teacherName, type);
        for (RecordCourse recordCourse : recordCourseCountList) {
            map.put("inSchoolCount", recordCourse.getInSchoolCount());// 在校学员
            map.put("outSchoolCount", recordCourse.getOutSchoolCount());// 离校学员
            map.put("notSchoolCount", recordCourse.getNotSchoolCount());// 未到学员
        }
        resultData.put("studentCount", map);

        return new Result(Code.OK, resultData, Code.GET_OK_MSG);
    }

    /**
     * 手动签退、交卷
     */
    @PostMapping("/updateStudentSignOff")
    public Result updateStudentSignOff(@RequestBody Map<String, String> map) {
        String studentSignInId = map.get("studentSignInId");
        String outDateTime = map.get("outDateTime");
        String type = StringUtils.isNotBlank(map.get("type")) ? map.get("type") : "1";
        StudentSignIn studentSignIn = iStudentSignInService.getById(studentSignInId);

        String status = "签退";
        if (type.equals("2")) {
            status = "交卷";
        }

        if (studentSignIn == null) {
            return new Result(Code.ERROR, "", "该学员签到记录不存在");
        }

        LocalDate currentDate = LocalDate.now(); // 获取当前日期
        if (!studentSignIn.getAddDate().equals(currentDate)) {
            return new Result(Code.ERROR, "", status + "时间已过期，无法手动" + status);
        }

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime outDateTimeParsed = LocalDateTime.parse(outDateTime, formatter);
        if (outDateTimeParsed.isBefore(studentSignIn.getInDateTime())) {
            return new Result(Code.ERROR, "", status + "时间不能小于签到时间");
        }

        if (type.equals("1")) {// 签退
            studentSignIn.setOutDateTime(outDateTimeParsed);
            studentSignIn.setType(2);
        } else if (type.equals("2")) {//交卷
            studentSignIn.setBrushDateTime(outDateTimeParsed);
        }

        iStudentSignInService.updateById(studentSignIn);

        return new Result(Code.OK, "", Code.SAVE_OK_MSG);
    }
}
